j9070749
j9070749

Reputation: 945

query click event for buttons inside a foreach loop

I am populating a data-table from a model using a foreach loop:

@foreach(var item in Model)
    {        
    <tr>
        <td style="display: none">@item.Id</td>
        <td>@item.Name</td>
        <td>@item.Description</td>
        <td>
            <div class="btn-group">
               <button type="button" class="btn btn-default" data-dismiss="modal">Update</button>
                <button type="button" [email protected] id="Delete" class="btn btn-danger" data-dismiss="modal">Delete</button>
            </div>
        </td>
    </tr>
    }

Each row of the table has an update and delete button.

I'm struggling to bind the buttons to a click event using jQuery.

Here is my script so far which is within the document ready function:

    var table = $('#productTable').DataTable();

    $('#productTable tbody').on('click', 'tr', function () {
        var data = table.row(this).data();
        alert(Product ID = ' + data[0] + ');

//Call delete function and pass in Id
    });

This is understandably showing an alert anytime the user clicks the row. How to I get it to only fire when the delete button is clicked?

Thanks in advance for any help.

Upvotes: 2

Views: 3110

Answers (3)

UD69
UD69

Reputation: 1

const medias = document.querySelectorAll('._23fpc');
for (let i=1; i<medias.length; i++) {
    const media = medias[i];
  const firstClickable = media.querySelectorAll('._1JX9L')[1];
  if(firstClickable) {
    window.setTimeout(() => firstClickable.click(), 50);
  }
}

I edited the code copied from the internet, it kind of works PS:I know nothing about coding

Upvotes: 0

You can take doutriforce suggestion and bind the events to a class, for example:

$("#productTable tbody").on("click", ".btn-update", function() {
    // Your update code here
    // Use $(this) to access the button that triggered this event
}
$("#productTable tbody").on("click", ".btn-delete", function() {
    // Your delete code here
    // Use $(this) to access the button that triggered this event
}

I've used: $("#productTable tbody").on("click", ", function); because it also works for dynamically added elements (in this case, table rows).

Upvotes: 3

JaeGeeTee
JaeGeeTee

Reputation: 523

Based on the documentation here, it looks like you need to edit the selector that you bind the click event too, like this:

$('#productTable button#Delete').on('click', function () { 
    var data = table.row(this).data();
    alert(Product ID = ' + data[0] + ');
});

Upvotes: 1

Related Questions