简体   繁体   中英

jQuery: Trigger even when checkbox gets checked

I am making a web app. In one part, I have a checklist dynamically generated with javascript.

I want to have a jQuery function executed when the checklist is checked.

Here is the code that dynamically generated the checklist:

var checkbox = document.createElement("input");
    checkbox.setAttribute("type","checkbox");
    checkbox.setAttribute("class", "tickbox");
    document.getElementById("sortable").appendChild(checkbox);

Here is the output HTML file on execution, that shows that the checkbox was actually created:

<input type="checkbox" class="tickbox">

I want to have a function executed when the box is checked. I have tried:

1.

 $('.tickbox').change(function () {
        alert("Here");
        if ($(this).attr("checked")) {
        alert("Yeah");
        }

2.

if($(.tickbox).is(':checked')){
      alert("Yeah!!!");

3.

$('.tickbox').each(function(){
    if($(this).is(':checked')){
      alert("Yeah!!!");
   }
   })

But nothing worked. What's wrong? What should I do?

Note: A lot of other javaScript and jQuery, including many other function calls are working completely fine.

You said you have dynamically added checkbox so in order to add event handler to that DOM you has to use .on() .

Example.

$(document).on('change','.tickbox',function(){
   if($(this).is(':checked')){
      alert("Yeah!!!");
   }
})

Try this....

var checkbox = document.createElement("input");
    checkbox.setAttribute("type","checkbox");
    checkbox.setAttribute("class", "tickbox");
    document.getElementById("sortable").appendChild(checkbox);
$(".tickbox").click(function(){
   if ($(this).is(':checked')) {
       alert("checked");
   }
});

Example: http://jsfiddle.net/7xY8Y/

for dynamically generated element you need to use on():

$(document).on("change",'.tickbox',function () {
   if ($(this).attr("checked")) {
   alert("Yeah");
 }
});

because your tickbox created dynamically then you need to bind event on document for class name tickbox for change event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM