Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  185] [ 2]  / answers: 1 / hits: 27526  / 8 Years ago, mon, december 19, 2016, 12:00:00

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


More From » html

 Answers
44

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>

[#59660] Friday, December 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;