0

I can easily catch click event of a checkbox as shown below:

<input type="checkbox" id="checkbox1" />

$('#checkbox1').change(function () {
    if (this.checked) {
        //Do stuff
    }
});

On the other hand, I create a checkbox on callback of AJAX (in jQuery DataTable) as HTML and click event of the same element cannot be catched:

//...
"ajaxSource": "/Student/GetStudents",
"fnServerData": function (sSource, aoData, fnCallback) {
    aoData.push({ "name": "all", "value": all });
    $.getJSON(sSource, aoData, function (json) {
        fnCallback(json);
        $("div.toolbar").html('<input type="checkbox" id="checkbox1" /> Get all records');
    });
},

What is the most suitable method to get the checkbox value in the HTML string?

1

1 Answer 1

3

The change event listener is created on all DOM elements that currently exists, so when you add the new checkbox the change method is not registered. Change your code to this.

$(document).on('change','#checkbox1',function() {
    //stuff
});
Sign up to request clarification or add additional context in comments.

7 Comments

It seems to work, but I cannot make checkbox retain its value as it is rendered on every callback of AJAX call. Is it possible? On the other hand, should I use the method in your answer in callback method? Or jquery onload?
What about using an hidden field?
The method does not go in the AJAX callback, it should go where you currently have it. To solve your issue, hold the checkbox value in a variable, and on AJAX callback set checkbox value to the saved value.
Could you please give an example of this by updating your answer? Thanks a lot...
On the other hand, what is the most suitable way for this situation? Using hidden field or cookie?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.