Adon
Adon

Reputation: 19

Use number from HTML text box in JavaScript equation

So I have some HTML code:

<input type="number" id="height">

I want to take whatever is entered in this box and use it as an int/float etc. Lets say I enter "2". Heres the JavaScript code:

var test;
var a;
test = document.getElementById('height').value;
a = 2 + test;

When I print a, I get 22. This makes sense, but I want 4. In other words, I want test to be treated as an int/float (whatever is entered in the text box). Is there an HTML input type that will do this for me, or do I have to change it another way (like JavaScript commands).

Upvotes: 1

Views: 121

Answers (2)

Eder
Eder

Reputation: 1884

Use the plus sign (+) a.k.a the unary plus operator as the first token for the variable assignment (rvalue), test = +document.getElementById('height').value

From developer.mozilla.org:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

Working Example

var test = +document.getElementById("height").value;
var a;

a = 2 + test;
alert(a);
<input type="number" id="height" value="5">

Upvotes: 2

Luke
Luke

Reputation: 2168

This is because test is a string, not a number. Use Number() to convert it to a number:

a = 2 + Number(test);

For your information, JavaScript is not Java - JavaScript is more for browsers, while Java is generally applied to more general situations - the syntax for each is vaguely similar, but still different. You are using JavaScript.

Upvotes: 1

Related Questions