Home > Software design >  jQuery - Call click event on dinamiclly created button in loop
jQuery - Call click event on dinamiclly created button in loop

Time:07-11

I have html table which i populate with content via ajax and php. I dinamiclly generate table rows and last column is row need to contain link/button where i need to call action for deliting that item (eg.Product) from table row.

I dont have idea how to call that specific ID becouse all is happening in loop each. Only in loop i have information about product id but in loop to call click() event not work and is so dumb for me. I think there is better solution to do that.

Check my code:

$.ajax({
            url: '/admin/dokument/5/edit?ajax',
            type: 'GET',
            success: function(response) {
                 
                response = $.parseJSON(response);

                $.each(response, function(i, item) {
                    i  ;
                    var $tr = $('<tr>').append(
                        $('<td>').text(i),
                        $('<td>').text(item.id),
                        $('<td>').text(item.name),
                        $('<td>').text(item.qty),
                        $('<td>').text(item.jm),
                        $('<td>').text(item.price),
                        $('<td>').text(item.discount),
                        $('<td>').text(item.pdv),
                        $('<td>').text(item.total),

                        <!-- this is for delete -->

                        $('<td >').html('<button type="button" id="product_' item.id '" ><i ></i></button>'),

                        
                        // This not work inside loop
                        $("#product_" item.id).click(function(e) {
                            alert(item.id);
                        }),

                    ).appendTo('#document_items_table > tbody');
                 });

             },
              complete: function(){
                $loading.hide();
              }

 

Do you have any idea how to execute this for specific product? Thanks!

CodePudding user response:

id attributes generated at runtime are an anti-pattern as they make the code more complex for no benefit.

To do what you require use a common class on all the buttons you generate, then you can use a delegated event handler along with DOM traversal methods to relate content to the button which was clicked.

$.ajax({
  url: '/admin/dokument/5/edit?ajax',
  type: 'GET',
  success: function(response) {
    response = $.parseJSON(response);    

    $.each(response, function(i, item) {
      var $tr = $('<tr>').append(
        $('<td>').text(  i),
        $('<td>').text(item.id),
        $('<td>').text(item.name),
        $('<td>').text(item.qty),
        $('<td>').text(item.jm),
        $('<td>').text(item.price),
        $('<td>').text(item.discount),
        $('<td>').text(item.pdv),
        $('<td>').text(item.total),
        $('<td >').html(`<button type="button" data-id="${item.id}" ><i ></i></button>`)
      ).appendTo('#document_items_table > tbody');
    });
  },
  complete: function() {
    $loading.hide();
  }
})

$('#document_items_table > tbody').on('click', '.btn-delete', function() {
  let id = $(this).data('id');
  console.log(id);
});

It's also worth noting that building HTML in JS as you are is not ideal. A better approach would be to use a <template /> element in your HTML and then clone that for each row. You can then also build a single HTML string which gets appended once. This will be faster than building 11 jQuery objects and appending to the DOM in every iteration of your loop.

  • Related