Solved

Using jQuery to get form input values and change PHP Variable

Posted on 2014-01-26
13
5,602 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
[X]
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
13 Comments
 
LVL 15

Expert Comment

by:Insoftservice
ID: 39811207
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 43

Accepted Solution

by:
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
    $('.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
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!
0
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
LVL 43

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
ID: 39813907
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
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?
0
 
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.
0
 
LVL 15

Expert Comment

by:Insoftservice
ID: 39814156
@JiveMedia did you tried my code ?
0
 

Author Comment

by:JiveMedia
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" />

etc.

Thanks.
0
 
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;
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
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 :)
0
 
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

0
 

Author Closing Comment

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

Expert Comment

by:Chris Stanyon
ID: 39817383
No worries ;)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Scroll listener getting fired on initial page load 2 20
Javascript: Range object 16 33
Editing .asp website 5 30
Div not showing up 6 31
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
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…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

737 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