I am making a form for users to input number and then trying to display the sum. But the document.getElementById('someid').value
is returning a string. And hence my add function is concatenating the strings instead of adding them as number. How do I solve it. Sorry for such a basic question.
//Script
function add(){
var a = document.getElementById('num1').value;
var b = document.getElementById('num2').value;
return a + b;
}
console.log(add());
//HTML
<p> Input 2 numbers to add</p>
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<input type="submit" value="Add" onclick="add()">
Try to use parseInt
. This function returns number
You have three options.
please please add the base 10 parsing to it, since you save the engine from trying to guess which base it should parse the integer to.
return parseInt(a, 10) + parseInt(b, 10);
the method i prefer is coercing String type to number type by simply wrapping the string in a number constructor
return Number(a) + Number(b);
3.unary plus
unary plus is the fastest and preferred way of converting something into a number. but Number(a) is much more readable in my opinion.
return +a + +b
Note: do not copy bad code from people parsing integers without giving it a base for parsing.
var a = parseInt(document.getElementById('num1').value);
You should prepend it with +
since they are strings and not numbers .
Try this:
function add(){
var a = document.getElementById('num1').value;
var b = document.getElementById('num2').value;
var x = +a + +b;
return x;
}
or, simply:
var a = parseInt(document.getElementById('num1').value);
var b = parseInt(document.getElementById('num2').value);
var x = a + b;
Modify your code instead:
<html>
<body>
<p>Input 2 numbers to add</p>
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<input type="submit" value="Add" onclick="add()">
<p id="result"></p>
<script>
function add(){
var a = document.getElementById('num1').value;
var b = document.getElementById('num2').value;
var x = +a + +b;
document.getElementById("result").innerHTML = x;
}
</script>
</body>
</html>
You have to tell javascript that you want to work with numbers instead of strings. So instead of
function add(){
var a = document.getElementById('num1').value;
var b = document.getElementById('num2').value;
return a + b;
}
you can use
function add(){
var a = document.getElementById('num1').value + 0;
var b = document.getElementById('num2').value + 0;
return a + b;
}
or
function add(){
var a = parseInt(document.getElementById('num1').value);
var b = parseInt(document.getElementById('num2').value);
return a + b;
}
parseInt(document.getElementById("id").value)
对于整数parseFloat(document.getElementById("id").value)
对于浮点数所以小数
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.