Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery click event on pagination overrides events for all the buttons

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=3. 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);
                }
            });
        })
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading