javascriptjqueryjquery-clone

jquery clone and add event


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


Solution

  • 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)