1

I am trying to fire an event on an array of checkboxes. The problem is, I believe, just because I add these checkboxes after the DOM has loaded the first time along with the JavaScript event handler the event handler can't fire on these new checkboxes when they are being clicked.

This is my code:

//this runs after the initial load of the page.
var fillSeries = function() {
    $.getJSON('api/series', function(data) {
    var result = '';
    for(var i = 0; i < data.length; i++) {

        //the first result is structure.
        if(i == 0)
            continue;

        var tablerow = '<tr><td><input type="checkbox" class="showarray" value="'+ data[i].id +'" /> ' + data[i].title + '</td></tr>';
        result += tablerow;
    }
    $('#series-table').append(result);
    // remove the loading icon and text
    $('#loading').remove();
});
}
// checkbox onclick listener
$('.showarray').click(function() {
    console.log($(this).val());
});

How can I make the event fire?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ms01
  • 4,420
  • 9
  • 48
  • 80

2 Answers2

1

Try attaching the event listener inside your callback, right after you append new content:
So instead of this: $('#series-table').append(result);, try:

$('#series-table').append(result).find('.showarray').click(function(e) {
    console.log($(this).val());
});
Onur Yıldırım
  • 32,327
  • 12
  • 84
  • 98
  • Thanks, this works just great. I tried to add it after before but I did it wrong :) – Ms01 Feb 17 '13 at 18:03
0

If it's correct that the issue is the result of elements being dynamically added to the DOM after page load, try using:

$(document).on('click', '.showarray', function() {
    console.log($(this).val());
});

This will handle click events for all elements with a classname of showarray, even if added dynamically after the page has been loaded.

EDIT: Looks like you already got it working, but I fixed my answer for the sake of completeness. .on() needs to be associated with a parent element to the element in question, and the actual selector being assigned the handler is the second argument.

squeezebox
  • 49
  • 6