views:

67

answers:

4

Hello,

I want to do this

var x=$(this).attr('id');
var y = x+1;

where x is an integer

but the value I get is x1

How do I do get the 16, if x=15?

Thanks Jean

+2  A: 
var y = parseInt(x) + 1;

should do the trick.

Andrew
+1  A: 

You need to tell JavaScript it's an integer using parseInt

var y = parseInt(x) + 1;
Mark E
+8  A: 

All the answers so far are missing the radix parameter

var x=parseInt($(this).attr('id'), 10);
var y = x+1;
Dan F
That's because it's an optional parameter and defaults to 10.
Dave Markle
@Dave: So what value do you think `parseInt('0123')` might return? https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/parseInt
LukeH
@Dave - Yes, optional, defaults to 10, [unless the string starts with 0](http://www.w3schools.com/jsref/jsref_parseInt.asp). It's a deprecated feature, but it still [bites](http://www.kipras.com/a-fact-about-javascript-parseint-that-i-wasnt-aware-of/105) [people](http://www.mgitsolutions.com/blog/2008/10/07/the-importance-of-the-javascript-parseint-radix/). My copy of chrome even does the deprecated thing, using [this test](http://jehiah.cz/archive/javascript-parseint-is-broken).
Dan F
@LukeH: Thanks for the article. Javascript strikes again. That's *awful*.
Dave Markle
+1  A: 
console.log(Number("23") + 1);   //24

I think you should be using Number() instead of parseInt because:

console.log(Number("23#") + 1);   //NaN
console.log(parseInt("23#") + 1); //24 (I would expect a NaN)
Amarghosh