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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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!
Turn Insights into Action

Communication across every corner of your business is essential to increase the velocity of your application delivery and support pipeline. Automate, standardize, and contextualize your communication processes with xMatters.

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.
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
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…
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…

690 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