10

I'm using jQuery to retrieve a value submitted by an input button. The value is supposed to be an integer. I want to increment it by one and display it.

// Getting immediate Voting Count down button id
var countUp = $(this).closest('li').find('div > input.green').attr('id');
var count = $("#"+countUp).val() + 1;
alert (count);

The above code gives me a concatenated string. Say for instance the value is 3. I want to get 4 as the output, but the code produces 31.

How can I change an HTML input value's data type to integer?

1
  • 1
    Side note: any text that comes from HTML is a string by default because HTML is, well, a string :) Commented Mar 16, 2011 at 15:11

5 Answers 5

22

To convert strValue into an integer, either use:

parseInt(strValue, 10);

or the unary + operator.

+strValue

Note the radix parameter to parseInt because a leading 0 would cause parseInt to assume that the input was in octal, and an input of 010 would give the value of 8 instead of 10

Sign up to request clarification or add additional context in comments.

1 Comment

There was a backwards incompatible change in EcmaScript which fixes the default-octal behaviour; any browser with a release in last 10 years or so parses it as decimal without an explicit 8 as second argument: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
6
parseInt(  $("#"+countUp).val()  ,  10  )

2 Comments

Yes. Otherwise you get results such as parseInt('010'); being 8.
@ptamzz - Yes, it does. The default is "try to guess".
2

Use parseInt as in: var count = parseInt($("#"+countUp).val(), 10) + 1; or the + operator as in var count = +$("#"+countUp).val() + 1;

Comments

0

There is a parseInt method for that or Number constructor.

Comments

0
var count = parseInt(countUp, 10) + 1;

See w3schools webpage for parseInt.

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.