Why doesn't the onclick method work without returning false?
The default action of a button inside a 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 when you click the button.
Why do values ββdisappear?
When the form is submitted, the page is redirected to the URL where the form is submitted. Since the action attribute is not specified, the form is submitted to the same page. And since no default values ββare set, the values ββare cleared when the page reloads.
How to solve a problem
You can stop this using return false; in the click event handler function as the last statement and adding return before the onclick attribute before the function in HTML.
Another thing you forgot to do is to specify a string in Number when values ββare read from the DOM element. Otherwise, + will be used as the string concatenation operator, and the result will be a concatenated string.
You can pass a string to a number by placing + (the unary + operator) before the string.
Updated script: 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 suggest / recommend
- don't use
table to format user interface, you can use div with simple styles - Move styles to a separate stylesheet and don't use inline styles.
- use
addEventListener to bind an event
source share