0

I have ajax call to get data from database and show the table row after success response. Inside the table row I have checkbox on it. I want to get selected index after the checkbox checked. I faces some problem when I set event handling to get selected index. This is my scripts.

<script type="text/javascript">
$("#buttonEdit").click(function(){
    var param1 = $('#param1').val();
    var param2 = $('.param2').val();

    var status = '';

    $.ajax({
        url: "<?=site_url()?>data/get_json", 
        type: "POST",    
        dataType:"json",  
        data: {"param1": param1, "param2": param2},
        success: function (response) 
        {
            if(response.length > 0)
            {
                $.each(response, function(i, item) {

                    var markup = "<tr><td><input type='checkbox' name='close' class='cls'></td><td><input type='text' name='price[]' value='"+response[i].price+"' readonly></td></tr>";
                    
                    $("table tbody").append(markup);
                });
            }
        }   
    });
});
</script>

<script type="text/javascript">
$(".cls").each(function(i) {
   if (this.checked) {
       alert("Checkbox at index " + i + " is checked.");
   }
});
</script>

I don't have problem with the ajax, my problem just inside second script to get the selected index. The script seems not working without any error.

Please anyone help me to solve this problem. Thanks.

Antonio
  • 729
  • 3
  • 11
  • 31
  • 2
    hint: you are adding the checkboxes to the dom. You need to use delegated events. See .on() api in jquery – Lelio Faieta Feb 18 '21 at 13:44
  • 2
    You are not doing any actual checkbox _event handling_ here in the first place. `$(".cls").each(function() {})` is _not_ event handling. That just applies the function once, to all elements with that class that existed in the document the moment this executes. – CBroe Feb 18 '21 at 13:45
  • 1
    as others said, what you are doing is basically checking the checkboxes before having it all in place. Probably the easiest way to see it in action is to move your `each` logic to a function and call it after your ajax success. – Renan Souza Feb 18 '21 at 13:47
  • @RenanSouza Thanks. Your method working well. – Antonio Feb 18 '21 at 13:52

0 Answers0