Home > Mobile >  jQuery click event on pagination overrides events for all the buttons
jQuery click event on pagination overrides events for all the buttons

Time:12-21

So I have some buttons for pagination and I was trying to add the click event for them. But this piece of code overrides the attached function. For example I have the buttons 1, 2 and 3. What I want to get: button 1 with id "pagination-1" to have attached the url with aggPage=1, button 2 with id "pagination-2" to be attached to aggPage=2, and so on. But this code overrides the url with the last value of i, so in this case, all the buttons will have attached url with aggPage=4. Why?

for (var i = 1; i <= numberOfPages; i  ) {
        var id = "#pagination-"   i;
        //this part looks right in the console
        console.log(id)
        console.log("/Home/ActiveAggregateLogs?aggPage="   i)
        $(id).click(function () {
            $.ajax({
                url: "/Home/ActiveAggregateLogs?aggPage="   i,
                type: "get",
                data: $("form").serialize(),
                success: function (result) {
                    $("#aggregations-table").html(result);
                }
            });
        })
    }

CodePudding user response:

The issue is caused by the fact that the value of i is not being captured by the closure created for the click event handler function. This means that the value of i used in the url property of the ajax call will always be the final value of i in the loop, which is numberOfPages.

One way to fix this issue is to use an immediately-invoked function expression (IIFE) to create a new scope for each iteration of the loop. This will allow you to capture the current value of i in a separate variable, which can then be used in the click event handler function. Here's an example of how you can modify your code to do this:

for (var i = 1; i <= numberOfPages; i  ) {
  var id = "#pagination-"   i;
  (function (i) {
    $(id).click(function () {
      $.ajax({
        url: "/Home/ActiveAggregateLogs?aggPage="   i,
        type: "get",
        data: $("form").serialize(),
        success: function (result) {
          $("#aggregations-table").html(result);
        }
      });
    });
  })(i);
}
  • Related