Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click() Not Executing for Cloned Element

I'm running into a bug with my code. I am cloning a div so that the user can add multiple customers.

            var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
            var newNum = new Number(num + 1);   // the numeric ID of the new input field being added
            var newElem = $('#divInput' + num).clone().attr('id', 'divInput' + newNum); // create the new element via clone(), and manipulate it's ID using newNum value

            // clear input value for cloned items and do not remove text for del button.
            newElem.find('input:not(.DeleteBtn),textarea').val('');
            //newElem.find('input[type="submit"]

            // Replace clone num with incremental num.
            newElem.find(':input').each(function () {
                $(this).attr('id', $(this).attr('id').replace(/\d+/, newNum));
                $(this).attr('name', $(this).attr('name').replace(/\d+/, newNum));
            });

            // insert the new element after the last "duplicatable" input field
            $('#divInput' + num).after(newElem);

I have provided a delete button to delete rows and I am using the class name for the button to execute a function on click .

        $(".DeleteBtn").click(function () {
            alert(".DeleteBtn Click Function -  " + $(this).attr('id'));
            var DelBtnNum = $(this).attr('id');
            DelBtnNum = DelBtnNum[DelBtnNum.length - 1];
            $('#divInput' + DelBtnNum).remove();

        });

I am able to delete the first (original) input row, but any additional customer rows are not deleted.

I have a running demo of the code located here: http://jsfiddle.net/crjunk/FB4BZ/2/

Why will the cloned items not fire the .DeleteBtn.click function?

like image 324
crjunk Avatar asked Mar 14 '14 16:03

crjunk


1 Answers

You need to use event delegation for supporting dynamic elements.

Since you have used jQuery 1.6 in the fiddle

$(document).delegate(".DeleteBtn", 'click', function () {
    alert(".DeleteBtn Click Function -  " + $(this).attr('id'));
    var DelBtnNum = $(this).attr('id');
    DelBtnNum = DelBtnNum[DelBtnNum.length - 1];
    $('#divInput' + DelBtnNum).remove();

});

if jQuery >= 1.7

$(document).on('click', ".DeleteBtn", function () {
    alert(".DeleteBtn Click Function -  " + $(this).attr('id'));
    var DelBtnNum = $(this).attr('id');
    DelBtnNum = DelBtnNum[DelBtnNum.length - 1];
    $('#divInput' + DelBtnNum).remove();

});

Another option is to clone the element along with the event using clone(true)

like image 166
Arun P Johny Avatar answered Nov 10 '22 06:11

Arun P Johny