Why onclick method is not working without return false. When i try to use it without return false it's show answer and then values disappear..
<form id="form1" method="POST">
<table style="border:1px solid black">
<tr>
<td>First Number</td>
<td>
<input type="text" id="first">
</td>
</tr>
<tr>
<td>Second Number</td>
<td>
<input type="text" id="second">
</td>
</tr>
<tr>
<td>Result</td>
<td>
<input type="text" id="result">
</td>
</tr>
<td>
<button id="btn" value="Add" onClick="addNumbers();return false;">Add</button>
</td>
</table>
</form>
Javascript:
function addNumbers() {
var firstNumber = document.getElementById('first').value;
var secondNumber = document.getElementById('second').value;
document.getElementById('result').value = firstNumber + secondNumber;
}
JSFIDDLE
Why onclick method is not working without return false?
The default action of button
inside the form
is to submit the form when you click on the button. To prevent this from happening you need to use e.preventDefault()
or return false
on the button click.
Why the values disappear?
When the form is submitted the page is redirected to the URL where form is submitted. As the action
attribute is not provided, the form is submitted to the same page. And as the default values are not set the values are cleared when the page is reloaded.
How to solve the problem
You can stop this from happening by using return false;
in the click event handler function as the last statement and adding return
before the onclick attribute before the function in the HTML.
One more thing you forgot to do is to cast the string to Number when the values are read from the DOM element. Otherwise +
will be used as string concatenation operator and the result will be a joined string.
You can cast the string to number by putting +
(unary + operator) before the string.
Updated fiddle: http://jsfiddle.net/tusharj/ufe7aqhw/
function addNumbers() {
var firstNumber = +document.getElementById('first').value;
var secondNumber = +document.getElementById('second').value;
document.getElementById('result').value = firstNumber + secondNumber;
return false;
}
<form id="form1" method="POST">
<table style="border:1px solid black">
<tr>
<td>First Number</td>
<td>
<input type="text" id="first">
</td>
</tr>
<tr>
<td>Second Number</td>
<td>
<input type="text" id="second">
</td>
</tr>
<tr>
<td>Result</td>
<td>
<input type="text" id="result">
</td>
</tr>
<td>
<button id="btn" value="Add" onClick="return addNumbers();">Add</button>
</td>
</table>
</form>
Sidenote:
I will suggest/recommend to
table
for formatting the UI, you can use div
with simple stylesaddEventListener
to bind eventBecause return false
is used to stop the default action of onclick
, which is submitting the form. And you obviously have not defined the post handler for your form. So if you submit your form, you will get an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With