16

I created my check box dynamically in my page. i want to add click event for all checkboxes that dynamically created.

here is my code.

<div data-role="fieldcontain">
         <fieldset data-role="controlgroup" id="br">

        </fieldset> 
</div>

i dynamically created checkboxes and append to fieldset.

$.getJSON("http://localhost/WebSite/",
    function(data){ 
    var branchOp="";
      $.each(data.branch, function(i,item){   
         branchOp += '<input type="checkbox" name="branch" id="'+item.branchCode+'" value="'+item.branchCode+'" class="branch"><label for="'+item.branchCode+'">'+item.branchName+'</label>'; 
         $(item.branchCode).addClass("intro");     
      });
      $('#br').append(branchOp).trigger( "create" );  
      });

i use on(), live(), deligate() method to add event handlers on check boxes.

$('#br').delegate('click','input:checkbox', function(event) {
  alert('selected');
 }); 



$('#br').on('click','input:checkbox', function(event) {
alert('selected');
});

nothing is working for me...

3 Answers 3

38

With checkbox / radio buttons, use change event.

Demo

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

Also, you can use click but on the div wrapping the checkbox.

$(document).on('click', 'div.ui-checkbox', function() {
  // code here
});
Sign up to request clarification or add additional context in comments.

1 Comment

I followed your sample and it worked fine but only small thing. I am using asp.net mvc with razor and I created checkbox like this <a Class="list-group-item" href="#" class="add"> @Html.DisplayFor(Function(Model) Model.name) @Html.CheckBoxFor(Function(Model) Model.isSelected) </a> I dont get checkbox is checked when I click inside hyperlink. is your one works because you create checboxradio instead. I dont know what is the difference even thought:)
2

For a dinamically added Button inside a Collapsible List (or anything) i do this:

$(document).on("click", "#listaEntrada input", function(evt) {
        var txSeleccionado = $(this).text(); //<-El Texto Seleccionado
        console.log(evt);
});

Comments

1

Try this, it's working for dynamically added checkboxes.

$(document).on("click", "INPUT[id^=checkboxId_]", function (event) {
   var targetId = event.target.id;

   if ($("#" + targetId + ":checked").length > 0) {
      alert('checked');
   }
   else {
      alert('unchecked');
   }
});

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.