I'm trying to piece together info from these two answers, but neither seems to cover the issue in a way that I can extrapolate and get to work for my situation. So please don't punish me if this seems like a duplicate; I don't think it is.
Increment multidimensional array when form fields are cloned
Copy table row and increment all name attributes
<tr>
<td><input type="text" name="pricing['prices'][0]['label']" value="" /></td>
<td><input type="text" name="pricing['prices'][0]['price']" value="" /></td>
<td><input type="text" name="pricing['prices'][0]['expires']" value="" /></td>
<td><input type="text" name="pricing['prices'][0]['bulk-price']" value="" /></td>
<td><input type="text" name="pricing['prices'][0]['bulk-qty']" value="" /></td>
</tr>
is what I'm trying to clone, using this button:
<input type="button" id="newRowButton" value="Add Another Price" />
Script (so far the cloning works, but it doesn't change the "0" to a "1". I'm clearly missing something that I couldn't figure out by piecing together the examples in the other two answers)
$("#newRowButton").live('click',function(e) {
e.preventDefault();
$("table.tablearray tr:last")
.clone()
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]$/,
function(str,p1){
return '[' + (parseInt(p1,10)+1) + ']';
});
})
.end()
.appendTo("table")
});
Any help would be appreciated. Ideally I'd also like to add a "delete row" button too.
Take out the $
sign from the regex so it's like this:
$("#newRowButton").live('click',function(e) {
e.preventDefault();
$("table.tablearray tr:last")
.clone()
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]/, function(str,p1){
return '[' + (parseInt(p1,10)+1) + ']';
});
})
.end()
.appendTo("table")
});
The $
was forcing it to look for [0]
at the end of the name which is not what you have.
Working demo here: http://jsfiddle.net/jfriend00/S9Q8W/
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