I've to implement a 'Add New Row' feature in a form. The structure of the form is something like:
<table>
<tr>
<td><input type="text" name="v1[label]" /></td>
<td><input type="text" name="v1[observation]" /></td>
<td><input type="text" name="v1[remarks]" /></td>
</tr>
<tr>
<td><input type="text" name="v2[label]" /></td>
<td><input type="text" name="v2[observation]" /></td>
<td><input type="text" name="v2[remarks]" /></td>
</tr>
<tr>
<td colspan="3">
<input type="button" id="addrow" value="Add One More Row">
<input type="submit" name="proceed" value="Submit" />
</td>
</tr>
</table>
As seen, with each row, there is an increase in v[]
number. v1, v2..and so on
WHAT I'M LOOKING FOR
When 'Add One More Row' button is clicked, the following things should happen
WHAT I TRIED
The closest I came to was using jQuery's
clone()
. This does add the row perfectly. But I'm finding it difficult to find a way to increase the value of the name attribute by 1 each time the button is clicked.
jQUERY BEING USED CURRENTLY
$('input:button[id="addrow"]').click(function(){
var secondlast = $('table tr:last').prev('tr');
secondlast.clone().insertBefore(secondlast);
});
If I click the button two times, I'm getting the following HTML added
<tr>
<td><input type="text" name="v2[label]" /></td>
<td><input type="text" name="v2[observation]" /></td>
<td><input type="text" name="v2[remarks]" /></td>
</tr>
<tr>
<td><input type="text" name="v2[label]" /></td>
<td><input type="text" name="v2[observation]" /></td>
<td><input type="text" name="v2[remarks]" /></td>
</tr>
So a row is being added, but the name attribute remains at v2, whereas it should be v3 and v4 for the third and fourth row. I understand clone()
can't do that and that is why I'm looking for an alternative.
$('input:button[id="addrow"]').click(function(){
var secondlast = $('table tr:last').prev('tr');
var newClone = secondlast.clone();
// find all the inputs within your new clone and for each one of those
newClone.find('input').each(function() {
var currentNameAttr = $(this).attr('name'); // get the current name attribute
// construct a new name attribute using regular expressions
// the match is divided into three groups (indicated by parentheses)
// p1 will be 'v', p2 will be the number, p3 will be the remainder of the string
var newNameAttr = currentNameAttr.replace(/^(v)(\d+)(.*)$/, function(match, p1, p2, p3) {
return p1+(parseInt(p2)+1)+p3;
});
$(this).attr('name', newNameAttr); // set the incremented name attribute
});
// insert after is I assume what you want
newClone.insertAfter(secondlast);
});
Edit
// you could also simply increment any digit you find as Batman indicated
var newNameAttr = currentNameAttr.replace(/\d+/, function(match) {
return (parseInt(match)+1);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With