0

I'm currently making a simple calculator for use in an intro to Javascript lesson. I would like to know if there's a simpler way of taking the value from a HTML input textbox as an integer than having to use the Javascript parse() method?

HTML:

<input type = "Text" id="num1">

JS:

var num1 = parseInt(document.getElementById("num1").value);
1
  • +document.getElementById("num1").value Commented Jun 22, 2014 at 20:36

1 Answer 1

1

You can force a string to be a 32-bit integer like this:

var num1 = ~~document.getElementById("num1").value;

You can, alternatively, accept a number with a possible fractional part with

var num1 = +document.getElementById("num1").value;

In both cases, you can check to see if the original string really did look like a number by using isNaN():

if (isNaN(num1)) {
  // bad input
}
Sign up to request clarification or add additional context in comments.

1 Comment

ha ha I answered the linked duplicate too. I have a one-track brain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.