Tim Wilkinson
Tim Wilkinson

Reputation: 3801

Set var as attribute value

I have a jQuery script that gives each div its own data-page-index attribute as a number, I have variables that pull specific data-page-index values and convert them to integers for some calculations, but i need to re-apply this number using its var name, for example,

var foo =  parseInt(active.attr('data-page-index')),
    next = (foo+1)
    nextfoo = $('[data-page-index="'' +next+ '"]')

is this possible?

Upvotes: 1

Views: 95

Answers (3)

Lix
Lix

Reputation: 47976

Yes it is possible. Your issue was a small syntax mistake. You had an extra single quote in there.

nextfoo = $('[data-page-index="'' +next+ '"]')
/* -----------------------------^---------- */

It is possible to see here on Stack Overflow thanks to the syntax highlighting that there is a problem. Your IDE should have also had the same effect.

The correct code should look something like this ( I don't really like defining multiple variables on one line so I've split them up -

var foo =  parseInt(active.attr('data-page-index'));
var next = foo+1;
var nextfoo = $('[data-page-index="' + next + '"]');

I could be wrong... but I think that next is a preserved keyword. This might be causing you some unpredictable issues... I recommend changing the name of that variable as well... Irrelevant

Upvotes: 1

Jai
Jai

Reputation: 74738

Absolutely :

var foo =  parseInt(active.attr('data-page-index')),
next = (foo+1) // <---parse this one too
nextfoo = $('[data-page-index="'' +next+ '"]')
   //---------------------------^--------------you have extra (') here

It should be :

var foo =  parseInt(active.attr('data-page-index')),
next = parseInt(foo+1);
nextfoo = $('[data-page-index="' +next+ '"]');

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Try this:

var foo =  parseInt(active.data('page-index')),
next = (foo + 1)
nextfoo = $('[data-page-index="' + next + '"]')

You had an erroneous double '' in the attribute selector.

Upvotes: 0

Related Questions