Rob M
Rob M

Reputation: 1031

Not catching on change event on checkboxs using jquery on

I have a list of questions that is getting loaded from a database when the page loads. I am parsing the list of questions, and added a checkbox to each question. I am planning on adding the id of each check box to an array which I am going to then pass back to the database for further processing.

$.each(data.d.crit1,function(key,value){
    var rowId = 'QID_0'+value.CLASS_QUESTION_ID;
    var codes = value.CODES ? value.CODES : '';
    $("#tblCrit1").append("<tr class='row' id='"+rowId+"'></tr>");
    $("#"+rowId).addClass('critical1').css('cursor','pointer')
        .append("<td class='chckbox'><input type='checkbox' id='cbx_Q"+value.CLASS_QUESTION_ID+"'/></td>")
        .append("<td>"+value.QUESTION_TEXT+"</td>")
        .append("<td>"+codes+"</td>");
});

I am attempting to attach an on change event handler to the check boxes, but for some reason, I cannot get the event to fire.

I've tried a few different methods that I thought should have worked. Something like:

$("input[type=checkbox]").on('change',function(){...});

and a few other permutations with no luck.

I'm apparently doing something wrong, but I can't seem to figure it out. Any help would be appreciated.

Upvotes: 0

Views: 43

Answers (2)

Andy Newman
Andy Newman

Reputation: 281

It's hard to know exactly without seeing context for the two excerpts, but I expect

$("input[type=checkbox]").on('change',function(){...});

May be being run before the method which adds the checkbox to the page. The on function will only be bound to elements that are on the page at the time it is run.

I would suggest either using

$(document).on('change', 'input[type=checkbox]', function () {...});

Which will attach the listener to document and any change events that bubble up and match the selector will trigger the callback.

Or attach the event listener to the input in the method that creates it, I think this would be neater.

Upvotes: 0

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

Try changing the selector $("input[type=checkbox]") to $("input[type='checkbox']")

EDIT: You should have ssomething like this:

$('#tblCrit1').on("click", "input[type='checkbox']", function(){...});

Attach the handler after loading the data.

Upvotes: 1

Related Questions