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
- A new row gets inserted just above the last row (the row with
buttons) - The name attribute value increases by 1 (i.e. v2[label] becomes
v3[label], v2[observation] becomes v3[observation] and so on) in that
row
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.
Edit