Reputation: 9
I don't know what is happening. I'm inputting value for the operation to solve but when it displays the result it displays but in a brief time only.
function add(){
var num1 = document.getElementById('fnum').value;
var num2 = document.getElementById('snum').value;
var ans = parseFloat(num1) + parseFloat(num2);
document.getElementById('res').value = ans;
}
<form>
1st Number:<input type="text" id="fnum" name="Num1" /><br>
2nd Number:<input type="text" id="snum" name="Num2" /><br><br>
<input type="submit" value="Add" id="button1" name="button" onclick="add()"/>
The result is:<input type="text" id="res" name="res" readonly="true" /><br>
</form>
Upvotes: 1
Views: 76
Reputation: 7149
Because you are using the <form>
tag with a <button type="submit">
, the form is submitted.
So what's happening is that your onclick
event is handled, but when that's done, the form is still submitted. You have multiple ways of fixing this:
<form>
<button>
type to button
Here's a working version without a <form>
tag and <button type="button">
:
function add() {
var num1 = document.getElementById('fnum').value;
var num2 = document.getElementById('snum').value;
var ans = parseFloat(num1) + parseFloat(num2);
document.getElementById('res').value = ans;
}
1st Number:<input type="text" id="fnum" name="Num1" /><br>
2nd Number:<input type="text" id="snum" name="Num2" /><br><br>
<input type="button" value="Add" id="button1" name="button" onclick="add()" />
The result is:<input type="text" id="res" name="res" readonly="true" /><br>
Upvotes: 2
Reputation: 283
it's because your button is a submit component, change :
<input type="submit" value="Add" id="button1" name="button" onclick="add()"/>
to
<button type="button" value="Add" id="button1" name="button" onclick="add()">add</button>
a submit component used to submit your form so you'll need a valid action in your form for that. or you can use onsubmit event for your form to prevent default form action
Upvotes: 0