Using jQuery to get form input values and change PHP Variable

Posted on 2014-01-26
Last Modified: 2014-01-29

I have made a booking form using some jQuery and HTML (with a lot of help), as you can see here:

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!
Question by:JiveMedia
  • 6
  • 5
  • 2
LVL 15

Expert Comment

ID: 39811207
Try out this one

<!DOCTYPE html>
  Created using
  Source can be edited via
<script src=""></script>
<meta charset=utf-8 />
<title>Booking Form</title>

<style id="jsbin-css">

    <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>
    <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)' />
	          <input name="pname_hid" type="text" class="required" id="pname_hid" size="30" />

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);

$("#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);
  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>';
  $('#participants .input_area').html(y);

<script src=""></script>
<script src=""></script>
<script src=""></script>

Open in new window

LVL 43

Accepted Solution

Chris Stanyon earned 500 total points
ID: 39812176
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
    //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
    //concatenate the names with a Pipe (|)
    listOfNames = names.join('|');
    //update your hidden field

Open in new window

Working Demo:

Author Comment

ID: 39813833
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!
LVL 43

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
ID: 39813907

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.

Author Comment

ID: 39814051
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?
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39814073
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.
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

LVL 15

Expert Comment

ID: 39814156
@JiveMedia did you tried my code ?

Author Comment

ID: 39816978
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" />


LVL 43

Expert Comment

by:Chris Stanyon
ID: 39817263
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;

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.

Author Comment

ID: 39817339
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 :)
LVL 43

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
ID: 39817355
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


Author Closing Comment

ID: 39817366
Great work Chris Stanyon...thanks for all your awesome work! :)
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39817383
No worries ;)

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

895 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

13 Experts available now in Live!

Get 1:1 Help Now