Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a numeric string by +1 with Javascript/jQuery

Tags:

I have the following variable:

pageID = 7

I'd like to increment this number on a link:

$('#arrowRight').attr('href', 'page.html?='+pageID);

So this outputs 7, I'd like to append the link to say 8. But if I add +1:

$('#arrowRight').attr('href', 'page.html?='+pageID+1);

I get the following output: 1.html?=71 instead of 8.

How can I increment this number to be pageID+1?

like image 266
JayDee Avatar asked Jul 02 '12 13:07

JayDee


2 Answers

Try this:

parseInt(pageID, 10) + 1

Accordint to your code:

$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
like image 141
antyrat Avatar answered Oct 22 '22 03:10

antyrat


+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.

$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
like image 21
Oleg V. Volkov Avatar answered Oct 22 '22 04:10

Oleg V. Volkov