-2

How to do something like this in a loop? Or is there a better way to do it?

      $('#btndelete' + rowid[i]).click(function(){
      $.ajax({
        type: "POST",
        url: "delete.php?id=rowid[i]",
        success: function(a) {
                $('#div-content').html(a);
        }
    });
});
KSiiP
  • 3
  • 4

1 Answers1

0

You can put it in a loop, by giving the handlers something to close over that won't change, like an argument in a function call you make:

rowid.forEach(function(value) {
    $('#btndelete' + value).click(function() {
        $.ajax({
            type: "POST",
            url: "delete.php?id=" + value,
            success: function(a) {
                $('#div-content').html(a);
            }
        });
    });
});

(If rowid isn't an array, you can easily make it one with Array.from [ES2015, but shimmable] or Array.prototype.slice.call(rowid).)

More details here: JavaScript closure inside loops – simple practical example.

But, in this particular case, you don't need to create a bunch of handler functions; put the rowid[i] on the element and then use a single handler for all of them:

rowid.forEach(function(value) {
    $("#btndelete" + value).data("rowid", value);
});
$("[id^=btndelete]").click(function() {
    $.ajax({
        type: "POST",
        url: "delete.php?id=" + $(this).data("rowid"),
        success: function(a) {
            $('#div-content').html(a);
        }
    });
});

Now a single handler handles all of them.

Or if these buttons are added/removed dynamically, you might use event delegation on some container.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875