Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6021
  • Last Modified:

Using jQuery to get form input values and change PHP Variable

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
JiveMedia
Asked:
JiveMedia
  • 6
  • 5
  • 2
3 Solutions
 
InsoftserviceCommented:
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
 
Chris StanyonCommented:
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
 
JiveMediaAuthor Commented:
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
Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

 
Chris StanyonCommented:
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
 
JiveMediaAuthor Commented:
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
 
Chris StanyonCommented:
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
 
InsoftserviceCommented:
@JiveMedia did you tried my code ?
0
 
JiveMediaAuthor Commented:
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
 
Chris StanyonCommented:
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
 
JiveMediaAuthor Commented:
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
 
Chris StanyonCommented:
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
 
JiveMediaAuthor Commented:
Great work Chris Stanyon...thanks for all your awesome work! :)
0
 
Chris StanyonCommented:
No worries ;)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

  • 6
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now