1

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

Dhaval Mistry
  • 476
  • 1
  • 9
  • 17
  • 5
    you need to get the value `c = a.value + b.value;` – Pranav C Balan Dec 19 '16 at 05:22
  • 1
    Use `.value` for fetching values. Also note that values will be fetched as string. – Rajesh Dec 19 '16 at 05:23
  • Possible duplicate of [How get total sum from input box values using Javascript?](http://stackoverflow.com/questions/13540751/how-get-total-sum-from-input-box-values-using-javascript) – Rajesh Dec 19 '16 at 05:24
  • 1
    Possible duplicate of [Javascript, viewing \[object HTMLInputElement\]](http://stackoverflow.com/questions/15383765/javascript-viewing-object-htmlinputelement). Have you tried searching? – Sebastian Simon Dec 19 '16 at 05:24
  • Possible duplicate of http://stackoverflow.com/questions/11563638/javascript-how-to-get-value-of-text-input-field – Mairaj Ahmad Dec 19 '16 at 05:27

2 Answers2

3

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>
Himanshu Tanwar
  • 906
  • 6
  • 18
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>
Ray
  • 280
  • 3
  • 4