Reputation: 3311
I'm trying to clone a "div" and all inside it but one of the events disappear in the cloned div (I'm pretty new to web developing so ... I "cloned" a code found on SO).
The missing event is added with the following javascript:
var MyClass = document.querySelectorAll(".BtnOptList");
for (var ii = 0; ii < MyClass.length; ii++) {
MyClass[ii].addEventListener('click', H_S_Btns_Func, false);
}
Then, to clone the div, I use the following function:
$('#btnAddFlds').click(function () {
//Count "cloned divs" we currently have
//This will be also used as numeric ID of the new input(s) field(s) (1st have no number)
var DivNum = $('.SDetails').length;
// clone() element and update its id(s)
var newElem2 = $('.SDetails:first').clone().attr('id', function( i, val ) {
return val + DivNum;
});
// manipulate the id values of the input inside the new element
newElem2.find('input,.BtnOptList,.HideIt').each(function(){
$(this).attr('id', function( i, val ) {
return val + '_' + DivNum;
});
});
//Try to add function (DOESN'T WORK)
newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);
//I omitted other stuff
});
I've already tried clone(true,true) but doesn't worked
Upvotes: 2
Views: 2005
Reputation: 6546
According to the documentation using clone with true
means
A Boolean indicating whether event handlers and data should be copied along with the elements. (v1.4 onwards)
Hence, use
.clone(true)
instead of
.clone()
Ref: http://api.jquery.com/clone/
Upvotes: 4
Reputation: 2783
This (newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);
) is not how you use jQuery's each
. Have a look at https://api.jquery.com/each/
Spoiler:
newElem2.find('.BtnOptList').each(function(i,e){e.addEventListener('click', H_S_Divs_Func, false)})
PS: Since you're using jQuery, you can use it's own event methods and add the listeners to the whole list:
newElem2.find('.BtnOptList').on('click', H_S_Divs_Func, false)
Upvotes: 1