Reputation: 63667
I have a form where a user can dynamically add more fields.
Example:
<form>
<input name="school" type="text" />
<input name="degree" type="text" />
<button role="button">Add another school</button>
</form>
When the button is clicked, I would like to add 2 more inputs for another school & degree. Easily doable with jQuery.
What should I set for the new name
attributes? When I submit this form I want unique school & degree pairs.
Upvotes: 1
Views: 135
Reputation: 2809
You can have a hidden input the saves the count of the pairs
And when you click the button, you add new pair with name postfixed by the count ex:"school[i]", then increase the count..
And on the server-side, you read the count input then you loop from 0 to count-1 to read the pairs
Check this code http://jsfiddle.net/2jdmP/
<form>
<input name="pair_count" id="pair_count" value="1" type="hidden" />
<p>
<input name="school0" type="text" />
<input name="degree0" type="text" />
</p>
<button role="button" id="add_button">Add another school</button>
</form>
JS
$(document).ready(function(){
$('#add_button').click(function(){
var pair_count = $('#pair_count');
var count = parseInt( pair_count.val() );
$(this).before(' <p><input name="school'+ count +'" type="text" /> <input name="degree'+count+'" type="text" /> </p>')
pair_count.val( count+1 );
return false;
})
})
Upvotes: 1
Reputation: 766
You can always count the existing nodes and create new ones.
Assuming the base fieldset to have an id qual
The following code can do the job:
var nextIndex = $('#qual > fieldset').length+1;
var next_row='<fieldset id="pair'+nextIndex+'"><input type="text" name="school'+nextIndex+'"/><input type="text" name="degree'+nextIndex+'"/></fieldset>';
$('#qual').append(next_row);
You can view the working example on js fiddle: http://jsfiddle.net/hunkyhari/4QUXz/
Upvotes: 1
Reputation: 5314
If you are using PHP you can
<input name="school[]" type="text" />
<input name="degree[]" type="text" />
Upvotes: 0
Reputation: 10040
You could make them an array....
<form>
<input name="school[]" type="text" />
<input name="degree[]" type="text" />
<button role="button">Add another school</button>
</form>
Upvotes: 1