Solved

Using jQuery to get form input values and change PHP Variable

Posted on 2014-01-26
13
5,365 Views
Last Modified: 2014-01-29
Hi,

I have made a booking form using some jQuery and HTML (with a lot of help), as you can see here: http://jsbin.com/AgEZONE/1/

Im trying to figure out how to get all the text inputted (in the selected amount of form inputs) and change the value of a hidden field on the page with a string put together from all the entered values.

So for example, if...
Number of Learners = 3
Learner Full Name: Greg
Learner Full Name: Aaron
Learner Full Name: Jason

The hidden input value on the page would equal = "Greg | Aaron | Jason".

Help would be greatly appreciated. Thanks!
0
Comment
Question by:JiveMedia
  • 6
  • 5
  • 2
13 Comments
 
LVL 15

Expert Comment

by:Insoftservice
Comment Utility
Try out this one

<!DOCTYPE html>
<html>
<!--
  Created using jsbin.com
  Source can be edited via http://jsbin.com/AgEZONE/1/edit
-->
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>Booking Form</title>

<style id="jsbin-css">

</style>
</head>
<body>
  <form>
    <div class="user_bf_input">
      <label for="course_qty">Number of Learners:</label>
      <select name="course_qty" id="course_qty" class="course_qty">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
      </select>
    </div>
    <div id="participants">
      <div class="input_area">
        <div class="user_bf_input">
          <label>*Learners Full Name:</label>
          <input name="pname[]" type="text" class="required" id="pname0" size="30" onmouseout='hiddenT(this,0,1)' />
        </div>
      </div>
    </div>
	          <input name="pname_hid" type="text" class="required" id="pname_hid" size="30" />

  </form>
<script>
function hiddenT(tot)
{
  var d='';
     for(i=0; i<tot; i++) {
		
		val =$('#pname'+i).val();
		//remove these if condition u want to maintain the sequence 
		if(val != "")
		{
			d += val+"|";
		}
	}
	d= d.substring(0, d.length - 1);
$('#pname_hid').val(d);

}
$("#course_qty").change(function() {
  var price = parseFloat($('#course_cost').val(), 10);
  var qty = (parseInt($('#course_qty').val(), 10) || 0);
  var total = (price * qty).toFixed(2);
  $("#course_total").val(total);
  var x = $('#course_qty').val();
  var y = '';
  for(i=0; i<x; i++) {
    y = y+'<div class="user_bf_input"><label>*Learners Full Name</label><input id="pname'+i+'" name="pname[]" type="text" class="required" size="30" onmouseout="hiddenT('+x+')"/></div>';
  }
  $('#quantity').val(x);
  $('#participants .input_area').html(y);
	});

	
</script>
<script src="http://static.jsbin.com/js/render/edit.js"></script>
<script>jsbinShowEdit({"root":"http://static.jsbin.com","csrf":"nylyJQfejTr9H/M77RXGer7h"});</script>
<script src="http://static.jsbin.com/js/vendor/eventsource.js?3.10.1"></script>
<script src="http://static.jsbin.com/js/spike.js?3.10.1"></script>
\
</body>
</html>

Open in new window

0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
Comment Utility
Have a look at this:

//When the dropdown changes
$('#course_qty').change(function() {
    //copy the input
    input = $('.user_bf_input').eq(0).clone();
    //empty the input_area
    $('.input_area').empty();
    //add the right number of inputs
    for (var i=0; i < $(this).val(); i++) {
        $( input ).clone().appendTo( ".input_area" );
    }
});

//when each input changes
$('.input_area').on('change', 'input', function() {
    //create an array to hold the names
    var names = new Array();
    //loop through each input
    $('.input_area input').each(function() {
        //add each value to the array
        names.push($(this).val());
    })
    
    //concatenate the names with a Pipe (|)
    listOfNames = names.join('|');
    
    //update your hidden field
    $('#hiddenNames').val(listOfNames);
});

Open in new window

Working Demo: http://jsfiddle.net/ChrisStanyon/7P9zE/
0
 

Author Comment

by:JiveMedia
Comment Utility
Cheers Chris! That looks great so far!

Was wondering about a few more things...

If i click in the first field input and enter a name, it copies to the hidden field fine, but if i change the select drop down after entering in the first name, it copies that name to all the new inputs generated. How would i go about making all the new inputs clear if the user changes the amount after.

Also, for example, if i select 4 from the drop down, enter in 4 names they all copy to the hidden field fine once again, but if i then decide to change the amount down to 3 after, all 4 names remain in the hidden field and the inputs revert to the first name entered.

Lastly, i use the classes 'input_area' and and 'user_bf_input' a lot throughout the form, i assume we should add a new class to those divs so others aren't targetted or target #participants .input_area.

Help will be much appreciated!
0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
Comment Utility
OK.

To make the new inputs clear, we need to reset the value of the clone - .val('');

As well as clearing the inputs, we can set the value of the hidden field to blank - $('#hiddenNames').val('')

As for changing the class names, I've updated the fiddle to target within the #participants div. You may have to adapt to suit your form.

http://jsfiddle.net/ChrisStanyon/7P9zE/
0
 

Author Comment

by:JiveMedia
Comment Utility
Fantastic Chris, all works perfect now except one little issue. jQuery Validate doesn't seem to pick up validation on the inputs now when the number changes and the number of inputs change.

Any ideas?
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
It's probably because you're binding the validation when the page first loads (using a document ready block). That means the valdiation code is only bound to elements that exist when the page is first loaded and not to newly created elements, such as your inputs.

You'll need to bind the validation events to the newly created elements after you create them.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 15

Expert Comment

by:Insoftservice
Comment Utility
@JiveMedia did you tried my code ?
0
 

Author Comment

by:JiveMedia
Comment Utility
Cheers Chris!

One last question!

If i need to change the name on the inputs for each generated, how would i go about that?

For example
<input type="text" size="30" class="required" name="pname1" />
<input type="text" size="30" class="required" name="pname2" />
<input type="text" size="30" class="required" name="pname3" />

etc.

Thanks.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Normally, you just leave the name as an array - pname[] so that when the form is submitted you keep all the values together. You then just loop through them in your form handler script:

foreach ($_POST['pname'] as $name):
     echo $name;
endforeach;

Open in new window

If you name then pname1, pname2 etc, then your script will have to check for each variable individually, and you won't know how many there are.

That said, if you really want to rename them, then you just set the name attribute as you append them to the DOM:

for (var i=1; i <= $(this).val(); i++) {
    $( input ).clone().attr('name', 'pname'+i).appendTo( "#participants .input_area" );
}

Open in new window

You'll notice I've changed the for loop slightly so it starts at 1 (var i=1) and not 0. I've updated the fiddle so you can see it working.
0
 

Author Comment

by:JiveMedia
Comment Utility
Hey Chris,

In your last code snippet...the name is getting appended to the divs 'user_bf_input' and not the form inputs.

Another line of code required to clone the inputs then append different names to each?

Otherwise it works fine.

Thanks :)
0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
Comment Utility
Oops! It's because I've called the DIV input - confused myself :)

Just change the name attribute before cloning:

for (var i=1; i <= $(this).val(); i++) {
    $('input', input).attr('name', 'pname'+i);
    $( input ).clone().appendTo( "#participants .input_area" );
};

Open in new window

0
 

Author Closing Comment

by:JiveMedia
Comment Utility
Great work Chris Stanyon...thanks for all your awesome work! :)
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
No worries ;)
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

5 Experts available now in Live!

Get 1:1 Help Now