class not working perfectly on dynamically generated button jQuery, Bootstrap

I'm generating a table using jQuer, Ajax . All the thing working fine but the edit button not working perfectly. I want to copy all data-(properties) on click. If I do the same with php it works fine, But I need using jquery. here is my code.

==================== table code ===========

$("#get_spare_list").click(function() {
    var ht = "";
    $.ajax({
        url: "<?php echo base_url('Spare/get_all_spare_json'); ?>",
        type: 'POST',
        dataType: 'json',
        data: {"param1": 'value1'},
    })
    .done(function(data) {
        var no = 1;
        var ht = "<table class='table'><thead><tr><th>No</th><th>Name</th><th>Code</th><th>Min qty</th><th>uni</th><th>Group</th><th>Sub Category</th><th>Part Number</th><th>Location</th><th>Image</th><th>Barcode</th><th>Tyre</th><th>Back</th></tr></thead>";
        $.each(data, function(key, val) {
            ht +="<tr>"+"<td>"+no+"</td>"+"<td>"+val.name+"</td>"+"<td>"+val.code+"</td>"+"<td>"+val.min_qty+"</td>"+"<td>"+val.unit+"</td>"+"<td>"+val.group+"</td><td>"+val.sub_category+"</td><td>"+val.part_number+"</td><td>"+val.location+"</td>";
            if (val.image) {
                ht += "<td><a target='_blank' href='"+"<?php echo base_url('../images/'); ?>/"+val.image+"'><button class='fa fa-picture-o'></button></a></td>";
            }else{
                 ht += "<td></td>";
            }
            ht += "<td><button class='btn btn-info btn-xs' onclick=PrintBar('val.code')>Print</button></td>";
            ht +="<td>"+val.tyre+"</td>";
            ht += "<td>";
                if (val.reusable) {
                    ht +="yes";
                }else{
                    ht+="no";
                };
            ht += "</td>";
            ht += "<td><button class='btn edit btn-info btn-xs' data-toggle='modal' data-target='#editModel' data-id='"+val.id+"' data-name='"+val.name+"'  data-code='"+val.code+"'  data-min_qty='"+val.min_qty+"'  data-unit='"+val.unit+"'  data-group='"+val.group+"'  data-sub_category='"+val.sub_category+"' data-part_number='"+val.part_number+"' data-location='"+val.location+"'  data-tyre_number='"+val.tyre+"' data-back='"+val.reusable+"'><span class='fa fa-edit'></span></button></td>";
            ht += "</tr>";
            no++;
        });
        $("#js_res").append(ht);
        console.log(ht);
    })
    .fail(function() {
        alert("error");
    });
});

======== Class code to copy data ============

$(".edit").click(function() {
    $("#id").val($(this).data('id'));
    $("#name").val($(this).data('name'));
    $("#code").val($(this).data('code'));
    $("#min_qty").val($(this).data('min_qty'));
    $("#unit").val($(this).data('unit'));
    $("#group").val($(this).data('group'));
    $("#sub_category").val($(this).data('sub_category'));
    $("#part_number").val($(this).data('part_number'));
    var location = $(this).data('location');
    var l1 = location.split("->");
    $("#room").val($.trim(l1[0]));
    $("#rake").val(l1[1]);
    $("#line").val(l1[2]);
    $("#box").val(l1[3]);
    if ($(this).data('tyre_number')) {
        $("input[name=tyre][value=" + $(this).data('tyre_number') + "]").prop('checked', true);
    }else{
        $("input[name=tyre][value='']").prop('checked', true);
    };
    if ($(this).data('back') == "1") {
        $("#back").attr('checked', true);
    }else{
        $("#back").removeAttr('checked');
    };
});

Answers:

Answer

Instead of click function you can use .on() function

$(document).on('click','.edit', function() { will bind the event on the .edit elements which are not present at the time of binding event. This is called event delegation

$(document).on("click", ".edit", function() {

    // your code here
})
Answer

This is because the element is dynamically generated, so does not exist on initial page load.

Use $.fn.on()

From the documentation

$(staticAncestors).on(eventName, dynamicChild, function() {});

In your case, it would be:

$(document).on("click", ".edit", function() {

    $("#id").val($(this).data('id'));
    $("#name").val($(this).data('name'));
    $("#code").val($(this).data('code'));
    $("#min_qty").val($(this).data('min_qty'));
    $("#unit").val($(this).data('unit'));
    $("#group").val($(this).data('group'));
    $("#sub_category").val($(this).data('sub_category'));
    $("#part_number").val($(this).data('part_number'));
    var location = $(this).data('location');
    var l1 = location.split("->");
    $("#room").val($.trim(l1[0]));
    $("#rake").val(l1[1]);
    $("#line").val(l1[2]);
    $("#box").val(l1[3]);
    if ($(this).data('tyre_number')) {
        $("input[name=tyre][value=" + $(this).data('tyre_number') + "]").prop('checked', true);
    }else{
        $("input[name=tyre][value='']").prop('checked', true);
    };
    if ($(this).data('back') == "1") {
        $("#back").attr('checked', true);
    }else{
        $("#back").removeAttr('checked');
    };
})

For more detail on why this doesn't work, see: Event binding on dynamically created elements?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.