Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding events to dynamically created checkbox in jquery mobile

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...

like image 868
bijin Avatar asked Aug 22 '13 10:08

bijin


People also ask

How do I add a dynamic event handler to a checkbox?

You can bind event handlers to dynamically created elements the same way you assign an id to them, such as by doing 'li. onclick = checkCount;' , where checkCount is the name of the function you want to assign to the handler.


2 Answers

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
});
like image 117
Omar Avatar answered Sep 22 '22 16:09

Omar


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);
});
like image 37
Jhollman Avatar answered Sep 21 '22 16:09

Jhollman