rozero
rozero

Reputation: 149

Strange behaviour of values from tag

let's suppose the value of ${currentPage} is 5 i.e. we are on the fifth page

there are two links:

<a id="idArrow" href="#" data-currentpage="${currentPage-1}" title="${currentPage-1}">backward</a>
<!-- the title displays 4 -->

<a id="idArrow" href="#" data-currentpage="${currentPage+1}" title="${currentPage+1}">forward</a>
<!-- note, the title displays 6, it seems ok-->

a script to get a value:

$('body').on('click', '#idArrow', function() {          
    console.log("running idArrow");
    var pageNumber = $("#idArrow").data('currentpage');
    console.log('pageNumber '+pageNumber);
...

now the most interesting part... if I press backward link then I get

running idArrow

pageNumber 4

if I press forward link then I get the same! how can it be?

running idArrow

pageNumber 4

Upvotes: 0

Views: 28

Answers (2)

trincot
trincot

Reputation: 350147

You could use the this object provided by jQuery to event handling functions:

    var pageNumber = $(this).data('currentpage');

Note that you should use unique id properties. $("#idArrow") refers to the first node with that id, and explains the behaviour you describe.

It would therefore be better to give a different selector to the on handler, like for instance a class that the elements share:

<a class="clsArrow" ... >

Code:

$('body').on('click', '.clsArrow', function(e) {      
    ...
    var pageNumber = $(this).data('currentpage');

Upvotes: 2

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9439

Do something like this:

<a id="idArrow1" href="#" data-currentpage="${currentPage-1}" title="${currentPage-1}">backward</a>
<!-- the title displays 4 -->

<a id="idArrow2" href="#" data-currentpage="${currentPage+1}" title="${currentPage+1}">forward</a>
<!-- note, the title displays 6, it seems ok-->

javascript

$('body').on('click', '#idArrow1', function() {          
    console.log("running idArrow1");
    var pageNumber = $("#idArrow1").data('currentpage');
    console.log('pageNumber '+pageNumber);
...

$('body').on('click', '#idArrow2', function() {          
    console.log("running idArrow2");
    var pageNumber = $("#idArrow2").data('currentpage');
    console.log('pageNumber '+pageNumber);
...

Your issue is that you have 2 of the same id's make them unique and it should solve your issue

Upvotes: 1

Related Questions