Search code examples
javascriptjqueryclone

Click event on cloned element of same class


I am cloning a row when a button is pressed in a row. The row contains the button being pressed, therefore when cloned a new row is added below, meaning there is another button. The button states "Add" but changes to "Remove" when add is pressed. The problem I'm having is that I want the click() function to check the last instance of the button/class, instead but it remains checking the original button. I want it to check the last button.

Take a look at the jsfiddle to see what I am trying to do:

http://jsfiddle.net/Fogest/4gdJk/

My issue is not changing the name of the buttons to "Remove", but I want to know how should I be applying this click function to the last button that is added?

Edit: Using jQuery v1.6.1


Solution

  • Use .on instead .click here is documentation

    $(document).on("click", ".add-remove-new:last", function () {
        $('tr.newService:first').clone().insertAfter($('tr.newService:last'));
    });
    

    working demo

    or you can use .live for jquery 1.6.1

    $('.add-remove-new:last').live('click', function() {
        $('tr.newService:first').clone().insertAfter($('tr.newService:last'));
    });
    

    demo for 1.6.1