jquerybindingonclickonclicklistenerjquery-clone

Unable to add click event to a cloned object using jquery


Below is the sample code which i was trying to attach a click event to the cloned object but i couldn't do that i have tried a lot but i couldn't attach the click event to the object. Please check the code and give your valuable suggestions

$(document).ready(function(){
    var documentSelector = $('.clone-block')
    var arrayOfObjects = [{
    	name: "William", 
        gender: "Male",
        dateofbirth: "01-01-2017"
    }, 
    {
    	name: "Michale", 
        gender: "Female",
        dateofbirth: "01-01-2018"
    }, 
    {	
    	name: "John", 
        gender: "male",
        dateofbirth: "01-01-2019"
    },
    {
    	name: "tom", 
        gender: "male",
        dateofbirth: "01-01-2020"
    }];
    
    $.each(arrayOfObjects, function (ind, user){
    	var clonedObject = documentSelector.clone(true, true);       
        clonedObject.find('span').on('click', alertWhenClicked.bind(user));
        clonedObject.find('span').text(user.name);
        $('.link-p').append(clonedObject.html());
    });
    
    function alertWhenClicked () {
    	alert(this.dateofbirth);
    }
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="clone-block" >
	<p>Username : <span></span></p>
</div>
<div class="link-p" ></div>
</body>
</html>


Solution

  • $('.link-p').append(clonedObject.html());
    

    You are turning the object into html and that is being appended to the dom, which will not have any of the event bindings on it. Take off the .html()

    As an aside note, you should look into delegate bindings so you don't have to put an event binding on all these elements.

    $.each(arrayOfObjects, function (ind, user){
        var clonedObject = documentSelector.clone(true, true);
        //put the user on the element as a data object for easy reference
        clonedObject.data('user', user);
        clonedObject.find('span').text(user.name);
        $('.link-p').append(clonedObject);
    });
    
    //delegate bind the click event to the parent for the future child elements
    $('.link-p').on('click', '.clone-block', alertWhenClicked);
    
    function alertWhenClicked () {
        alert($(this).data('user').dateofbirth);
    }