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?

Jack
  • 1
  • 15
  • 75
  • 149
  • You need to use the jQuery on() method. http://stackoverflow.com/questions/10082031/why-use-jquery-on-instead-of-click – c-bro Oct 04 '16 at 17:07

1 Answers1

2

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
});
Hurricane Development
  • 2,301
  • 1
  • 14
  • 36
  • 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? – Jack Oct 04 '16 at 17:30
  • What about using an hidden field? – Jack Oct 04 '16 at 17:39
  • 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. – Hurricane Development Oct 04 '16 at 17:50
  • Could you please give an example of this by updating your answer? Thanks a lot... – Jack Oct 04 '16 at 17:55
  • On the other hand, what is the most suitable way for this situation? Using hidden field or cookie? – Jack Oct 04 '16 at 17:55
  • Any idea regarding to this issue? – Jack Oct 04 '16 at 18:57
  • Sounds like a different question now, post a new question. – Hurricane Development Oct 04 '16 at 21:18