简体   繁体   中英

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].

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>
<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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM