2
<script>
    $(document).ready(function(){
        $("#city").change(function(){
            name = $(this).val();
            $.ajax({
               type:"GET",
               dataType: "json",
               data:{name: name},
               dataType: 'json',
               contentType: "application/json; charset=utf-8",
               url:"test.php",
               async:false,
               success:function(data)
               {
                    $.each(data.PostOffice, function(key, item) {

                        $("#pincode").append("<li><input type='checkbox' id='"+item.PINCode+"' name='pin' class='pin'/>"+item.Name+"</li>");
                    });
               }
            });
        });

        $(".pin").on('click',function(){
            pin = this.id;
            alert(pincode);
        });
    });
</script>

In this code I am using append function inside the each loop as you can see above the code. Now, What happen I have multiple checkbox when I change city but when I use $(".pin").on('click',function(){ to get the id of checkbox it doesn't work. So, How can I get id onclick class="pin"? Please help me.

Thank You

Rudra
  • 136
  • 2
  • 12

1 Answers1

1

Since you are adding the HTML for checkbox inside AJAX call dynamically after the page has been loaded, the function $(".pin").on('click',function(){}) will not work as it will not find element with .pin class on page load. So, you need to assign a click event from the document reference as:

$(document).on('click','.pin', function(){
    pin = this.id;
    alert(pin);
});
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55