0

So I have a list I wan to clone and add new entries for:

<li class="splashEntry" data-counter="0">
    <select name="options[0][type]" class="textCtrl">...</select>
    <select name="options[0][sort]" class="textCtrl">...</select>
</li>

I am closing the field using $('li.splashEntry').last().clone() and getting the counter value using .data('counter').

My question now would be, what would be the best way to update the data-counter field, and the select names in the subsequent created clone? Ideally, the cloned list item should have an incremented data-counter and select names. So the cloned field, which will appended to the end should be:

<li class="splashEntry" data-counter="1">
    <select name="options[1][type]" class="textCtrl">...</select>
    <select name="options[1][sort]" class="textCtrl">...</select>
</li>

Then since this new entry is appended to the end; if I click the button to create another clone, it should read the new data-counter as 1 (instead of 0 on the first row), and then create a new list item where all the entries say 2.

What would be the best way to achieve this?

1 Answer 1

1

Try something like

//cloned element
var $clone = $('li.splashEntry').last().clone(),
    //find the new counter value using old one
    counter = $clone.data('counter') + 1;
//update the data-counter attibute - used attribute instead of data because it gives a visual update on the dom
$clone.attr('data-counter', counter);
//update the name values
$clone.find('[name]').attr('name', function (_, name) {
    return name.replace(/\[\d+\]/, '[' + counter + ']')

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

New question... do you know how I would unselect the selected option from the clone?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.