0

I have a row in a div with a button at the end, when I click on the button it logs in the console.

I add another row via jquery with the same class but when I click on the button on the second row the event does not fire.

See the example here https://jsfiddle.net/DTcHh/24037/

Click add (to add second row) then on 'X' for each row (whilst monitoring console). Only row 1 works for me

code also below: HTML

<div id="tasksTableDiv">
                            <div class="row" id="1">
                                <div id="description_1"
                                    class="col-sm-2 taskDescriptionCol">Description 1
                 </div>
                                <div class="col-sm-1 removeTaskCol">
                                    <input id="button_1" class="removeTaskButton" type="button" value="X">
                                </div>
                            </div>

</div>

<button id="addTaskButton" type="button"
                            class="btn btn-sm btn-primary">Add Task</button>

JS

$('.removeTaskCol').on('click', function(){
           console.log("Clicked X");
    });

  $('#addTaskButton').on('click',function() {
        $('#tasksTableDiv').append('<div class="row" id="2">'
                                + '<div id="description_2"'
                                + 'class="col-sm-2 taskDescriptionCol">Description 2'
                 + '</div>'
                                + '<div class="col-sm-1 removeTaskCol">'
                                    + '<input id="button_2" class="removeTaskButton" type="button" value="X">'
                                + '</div>'
                            + '</div>');

    });
Storms786
  • 416
  • 1
  • 7
  • 20
  • 1) Use a delegated event handler as you are dynamically appending the elements to the DOM - see the question I marked as duplicate for more info 2) hook the event to the click of the `input`, not its parent. – Rory McCrossan Aug 24 '16 at 21:09
  • when you are adding elements to the DOM dynamically, and have eventListeners attached to them, on page load, those elements may not exist. Any eventListeners that you may have set up for an element that may not exist will come up with a null target. To remedy, you should add the class of the element to the eventListener `.on('click','.class_name', function()` and this will tell jQuery to go look for that class that may not have existed previously. – HolyMoly Aug 24 '16 at 21:18
  • Ive modified it to be $('.removeTaskCol').on('click', '.removeTaskButton', function() but cant get it to work... can someone modify the jsfiddle for me and show me please??? i dont get it! – Storms786 Aug 24 '16 at 21:21
  • check this https://jsfiddle.net/naveencgr/DTcHh/24053/ which solves your issue – CNKR Aug 24 '16 at 21:29
  • Thanks @user3498863 you're 100% right :) – Storms786 Aug 24 '16 at 21:31

0 Answers0