0

Using JQuery I append a tr where one of the td's includes a checkbox. It appears nicely on the screen. However I want to select one of the checkboxes and trigger a function on click. For some reason the selector does not see the appended checkbox. I presume thta this is because the checkbox is not actually within the HTML source code.

So, Question: what do I do to select this checkbox ?

$.each(categories, function (i, product) {
    $(".table_products").append('<tr class="empty"><td >' + product.product_name + '</td><td>' + product.price + '</td><td> <input type="checkbox" value="cat_id"></td></tr>');

    $("tr").addClass("cat_products");
});

$("td input:checkbox").on('click', function () {
    alert('line 41');
});
Barmar
  • 596,455
  • 48
  • 393
  • 495
Vince
  • 981
  • 1
  • 12
  • 25
  • 2
    That code should work as long as you're running the `.on()` after the `$.each` loop. – Barmar Apr 12 '16 at 21:56
  • Works for me: https://jsfiddle.net/barmar/mybqnuy5/1/ – Barmar Apr 12 '16 at 21:59
  • Assuming your table is `.table_products` could you try something like this? `$('.table_products').on('click', 'td input:checkbox', function(){...`. This would attach the event listener to the table, and it would automatically be applied to newly appended checkboxes – David784 Apr 12 '16 at 22:00
  • If you're trying to bind the handler when the page is loaded, see http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Apr 12 '16 at 22:00
  • @David784 Bloody hell it worked ! I guess David's answer is essentially the same as Barmar. I'm new to JS, and I have to admit that I do not understand **why** is works. – Vince Apr 12 '16 at 22:16

1 Answers1

0

I have to give a brief description of how events work. In JavaScript, events "bubble." This means that if you click on a span, the span gets the click event first. Then the click event bubbles up to the parent of the span (let's say a div). Then the event bubbles from there to the next element in the chain. And so on, until you get to the top element of the DOM.

jQuery gives you the ability to attach event listeners to any level in the document. And it also gives you the ability to filter. So when we do this:

$('.table_products').on('click', 'td input:checkbox', function(){...});

We are attaching the event listener to the .table_products element. this element never changes. It's always there. What we added was the filter part, or the 'td input:checkbox'. This part tells jQuery, "when you get a click event inside the table, look and see if that click event happened on a child element which matches this filter."

This allows newly added elements to be picked up by the listener. Hope this explanation helps. You can get more information here

David784
  • 4,878
  • 1
  • 17
  • 25