1

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.

3 Answers 3

2

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!!!");
   }
})
Sign up to request clarification or add additional context in comments.

Comments

1

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/

1 Comment

Working fine when only one checkbox present but not with multiple. I am actually using multiple checkboxes.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.