I try to make some repeatable fields with PHP and Javascript. This works fine, but after saving the post (creating an plugin for WordPress) the cloned row will override the latest one. This is because I don’t use unique id’s for each row.
I want to add an ‘id’ attribute with javascript and I want for each row that is created with the id 1 increase. I had already done something similar with PHP, but found out that this is not what I wanted and I am better out with javascript, I think, because when I clone the field with the “add new” button the amount doesn’t increase with +1;
Here is the php code that I had used:
$count = 2;
for ($i = 0; $i < $count; $i++) {
// Begin a table row
echo '<tr class="row" id="' . '['.$i.']' . '-repeatable">';
echo '<td class="order">' . '['.$i.']' . '</td>';
// Do cool stuff inside the row
echo '<td class="remove"><a class="repeatable-remove button" href="#">-</a></td>';
echo '</tr>'; // End .row
} // End for loop
<a href"#" class="button">Add new row</a>
JS code for the repeatable fields:
// Add repeatable row
jQuery('.repeatable-add').click(function() {
// Clone row
var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child');
var clone = row.clone();
clone.find('input[type=text], text, textarea, select, input.upload_image').val(''); // Reset the values
clone.find('.preview_image').attr('src', ''); // Reset the values
row.after(clone);
//
return false;
});
I think I have to do something like this snippet of line:
clone.find('tr.row').attr('id', 'repeatable-' + addInteger);
But how do I increase with +1 inside Jquery/Javascript, like my example in PHP?
What you want to do is look at the ID of the row you’re cloning and use that ID to give the new row its proper index value. I added two lines of code to your example, one defining a new variable called
clonedIdIndexand one using the value in that variable to define a new ID for the cloned row.