Question

[Solved] javascript error [object HTMLInputElement][object HTMLInputElement]

i am practicing java script code but having issue while implementing this code.

<html>
<body>
<script>  
function f2(){
var a=document.getElementById("a");
var b=document.getElementById("b");
var c=a+b;
document.write(c);
}
</script>  

Enter A:<input id="a" type="text" name="txt1" ><br>
Enter B:<input id="b" type="text" name="txt2" ><br>
<button type="button" onclick="f2()">Sum Here</button>
</body>
</html>

When I add two numbers then it shows error like [object HTMLInputElement][object HTMLInputElement].

Solution #1:

The value property of input elements is used to retrieve the value enters in the input. This value will be a string.

Since you want to add numbers, it is better you check if the inputs entered are numbers to avoid unwanted bugs.
There are many ways to check this, one I’ve used it by adding ‘+’ sign in front of the entered string value, this will convert a number in string to a number and then check for NaN.

here is the fiddle and code
https://jsfiddle.net/7sgcmfu8/

<script>  
function f2(){
var a= +document.getElementById("a").value;
var b= +document.getElementById("b").value;
if(!isNaN(a) && !isNaN(b)){
    document.write(a+b);
}else{
    document.write("enter numbers");
}
}
</script>  

Enter A:<input id="a" type="text" name="txt1" ><br>
Enter B:<input id="b" type="text" name="txt2" ><br>
<button type="button" onclick="f2()">Sum Here</button>
Respondent: Himanshu Tanwar

Solution #2:

<html>
<body>
<script>  
function f2(){
var a=parseInt(document.getElementById("a").value);
var b=parseInt(document.getElementById("b").value);
var c=a+b;
document.write(c);
}
</script>  

Enter A:<input id="a" type="text" name="txt1" ><br>
Enter B:<input id="b" type="text" name="txt2" ><br>
<button type="button" onclick="f2()">Sum Here</button>
</body>
</html>
Respondent: Ray

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy