i am trying to make a maths engine with JavaScript and HTML.
Here is (https://i.stack.imgur.com/NCEa4.jpg)
The alert from the js alert() function works but the output from it is wrong:
'HTMLObject'
i am trying to make a maths engine with JavaScript and HTML.
Here is (https://i.stack.imgur.com/NCEa4.jpg)
The alert from the js alert() function works but the output from it is wrong:
'HTMLObject'
Use 'parseInt()'
function to convert those values to integers first and then add the values.
Value of the input field is always a string. So when you use +
operator with two strings it concatenates them. If you want to add two numbers you need first to convert strings to numbers. There are multiple ways to do it, for example:
var plus = parseInt(one) + parseInt(two);
Or you can use Number(one)
, or another unary + operator: +one + +two
, but this might look confusing.
You need to enclose your function code in curly braces {
& }
.
So Use:
function Maths(){
var one=document.getElementById("fid").value;
var two=document.getElementById("sid").value;
var plus=Math.parseInt(one)+Math.parseInt(two);
alert(plus);
}
Also use parseInt()
to make data type conversion to convert to int
in JavaScript.
Hope it'll help you. Cheers :)!!
Will be better if you use second argument in parseInt for be sure that value will be in decimal system.
function Maths() {
var one = document.getElementById("fid").value,
two = document.getElementById("sid").value,
plus = Math.parseInt(one, 10) + Math.parseInt(two, 10);
alert(plus);
}