andcl
andcl

Reputation: 3548

jQuery cloning divs from button click with incremental HTML data-id attribute

I am using Twitter Bootstrap CSS framework + jQuery to build an UI.

In my interface, I have several divs and an external button that clones the last of them when clicked and inserts it in the DOM in the "new" last position, like this:

$(document).on('click', 'button.addDiv', function() {
    var lastDiv = $(this).closest('.form-group').siblings().last();
    var id = lastDiv.data('id');
    var newDiv = lastDiv.clone(true);
    ...

Each div has a data-id HTML attribute with a number starting at 1, and I want the new dynamic divs to have subsequent ids. For that, I have:

    ...
    newDiv.attr('data-id', id + 1);
    newDiv.insertAfter(lastDiv);
});

Which does exactly what I want, but ONLY the first time the button is clicked... (i.e. data-id is correctly set to 2 only with divs already on page load, not dynamically added). However, second an subsequent times the button is pressed (when a dynamic div is "the last"), data-id remains 2 although the newDivs keep inserting (the right way) one after the last...

Any idea of what could be happening? Thanks in advance.

Upvotes: 1

Views: 81

Answers (1)

Hadas Zeilberger
Hadas Zeilberger

Reputation: 761

replace newDiv.attr('data-id',id+1) with newDiv.data( "id", id + 1 );

What's happening is that you are attaching data-id to the DOM element as an attribute. JQuery does not register this as the element's data. Then, since you are cloning the div, each cloned div maintains a data-id of 2.

Upvotes: 1

Related Questions