Reputation: 3021
I am trying to increment a form field ID so they are all different when i click on the plus to create a new row of input fields.
Here is my code so far
//Order Form
$("#add").click(function() {
$('#ordertable tbody>tr:last').clone(true).insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last #prodcode').val('');
$('#ordertable tbody>tr:last #meterage').val('');
$('td.imgsample:last a').remove();
return false;
});
On the first line within the click function how can i change the input fields (prodcode & meterage) to be prodcode1 meterage1 e.t.c
Upvotes: 3
Views: 2849
Reputation: 54605
Assuming you are going to do this more often then once.
//Somewhere global
var counter = 0;
//Order Form
$("#add").click(function() {
counter++;
var cln = $('#ordertable tbody>tr:last').clone(true);
cln.find("[id^='prodcode'], [id^='meterage']").each(function(i, val) {
val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
});
cln.insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last #prodcode').val('');
$('#ordertable tbody>tr:last #meterage').val('');
$('td.imgsample:last a').remove();
return false;
});
Of course there are "cleaner" solutions without using a global counter
For the problem mentioned in the first comment something along the lines of
$("tr [id^='prodcode'], tr [id^='meterage']").live("blur", function() {
....
$(this).val() //instead of $("#prodcode").val()
....
});
should do
Upvotes: 3
Reputation: 4820
$('#ordertable tbody>tr:last #prodcode')
.val('')
.attr(
'id', function(i,id) {
match = id.match(/\d+?$/);
if ( match.length ) { match++; return 'prodcode' + match } // could be match[0], may return array!
else return id + 1 // or '2' if you wish
}
);
same for next element.
Upvotes: 0