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

2

4 Answers 4

8

All the answers so far are missing the radix parameter

var x=parseInt($(this).attr('id'), 10);
var y = x+1;
Sign up to request clarification or add additional context in comments.

4 Comments

That's because it's an optional parameter and defaults to 10.
@Dave: So what value do you think parseInt('0123') might return? developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…
@Dave - Yes, optional, defaults to 10, unless the string starts with 0. It's a deprecated feature, but it still bites people. My copy of chrome even does the deprecated thing, using this test.
@LukeH: Thanks for the article. Javascript strikes again. That's awful.
2
var y = parseInt(x) + 1;

should do the trick.

Comments

1

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

var y = parseInt(x) + 1;

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.