Erica Stockwell-Alpert
Erica Stockwell-Alpert

Reputation: 4863

Buttons generated in for loop are not getting correct values

I have a dynamic webpage that displays a list of results, with multiple pages. I currently have functional "previous page" and "next page" buttons, but I want to add specific page buttons like many websites have, so that you can go to a page number directly rather than scrolling through the pages one at a time. To do this I am using a for loop to generate the page buttons, since the number of pages is variable. Here is my code:

@{ var val = 1;}
@for (var i = 1; i <= numPages; i++)
{
    <text> @val </text>
    <button type="submit" class="page-button" value="@val"> @i </button>
    val++;
}

The buttons are being generated, except all of them are getting a value of 1. This is how I'm testing what the buttons values are:

$(".page-button").on("click", function(event) {
    alert($(".page-button").val());
});

Every button pops up an alert that says "1" when it is clicked, even though @val is being incremented correctly (I can tell because @val displays the same number as the page button it is next to).

I also tried

<button type="submit" class="page-button" value="@i"> @i </button>

But again, even though the numbers displayed on the buttons were correct, when I clicked them they all had a value of 1. Why aren't the values being assigned correctly?

Upvotes: 1

Views: 68

Answers (1)

Nisse Engstr&#246;m
Nisse Engstr&#246;m

Reputation: 4751

I don't know JQuery, but I presume that $(".page-button").val() fetches all elements in the document with class="page-button" and returns the value of the first one. You need to obtain a reference to the current element which fired the event.

This seems to work for me:

alert($(this).val());

but I really don't know what I'm doing here.

Upvotes: 1

Related Questions