Form handling onsubmit, onchange, onselect, onblur, onfocus
2. onsubmit
Using this event handler will execute an action when the user clicks on the submit button. Let’s look at the code below for its sample use. Using onsubmit calls a JS function myFunction()and prints the entered username.
This code will also demonstrate how JS retrieves the input of the user from the textbox and uses that input for processing in JavaScript. The value property is used to get the value entered by the user in the input element. Remember how we used the innerHTML property to indicate the contents of an HTML element? The concept of value works the same way.
<form onsubmit="return myFunction();">
<label for="uname">Username: </label>
<input type="text" id="uname">
<input type="submit">
</form>
<p id="demo">
</p>
<script>
function myFunction(){
var x = document.getElementById("uname").value;
document.getElementById("demo").innerHTML = "Your input is " + x + ".";
return false;
}
</script>
Notice the use of return in calling the function from the onsubmit attribute and the return false line at the end of the function. We use a return value to help the onsubmit event handler determine what to do with the form. If the return value is true, the value from the form is sent to a server for processing and the server replies back. In our example, we are only dealing with client-side processes so we are returning false to make the browser stay on the current page and instruct the webpage to not send the values to a server. If you try to remove the return in the function, you will see that the desired display shows for a brief moment and then disappears. By adding a return false to out script, the browser will stay on the current page.