0

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

Dave Markle
  • 95,573
  • 20
  • 147
  • 170
X10nD
  • 21,638
  • 45
  • 111
  • 152

4 Answers4

8

All the answers so far are missing the radix parameter

var x=parseInt($(this).attr('id'), 10);
var y = x+1;
Community
  • 1
  • 1
Dan F
  • 11,958
  • 3
  • 48
  • 72
  • 2
    That's because it's an optional parameter and defaults to 10. – Dave Markle Jul 07 '10 at 11:24
  • 3
    @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 Jul 07 '10 at 11:35
  • 1
    @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 Jul 07 '10 at 11:39
  • 1
    @LukeH: Thanks for the article. Javascript strikes again. That's *awful*. – Dave Markle Jul 07 '10 at 11:47
2
var y = parseInt(x) + 1;

should do the trick.

Andrew
  • 777
  • 1
  • 7
  • 19
1

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

var y = parseInt(x) + 1;
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
1
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
  • 58,710
  • 11
  • 92
  • 121