Class 5 – How to Cancel the Default Behavior of Links and Forms
Posted: March 14th, 2009 | Author: amos | Filed under: javascript | Tags: class 5 | No Comments »Clicking a link and submitting a form will, by default, take you to another page. In some cases, you may want to override that behavior.
Canceling form submissions
To cancel the submission of a form, while still allowing the user to click a submit button, the form tag’s “onsubmit” attribute must be set to return false. This causes the browser to cancel the form submission after the user attempts to submit.
<form onsubmit="return false;">
See an example live on the server
Let’s say, in a hypothetical situation, you wanted to call a function in Javascript first when the user clicks submit, and then cancel the form, you could add the function call (or any other Javascript code) before the “return false;” statement.
For example, assuming you had a function named doSomething(), you could call it when the user tries to submit the form, and then cancel the form as follows:
<form onsubmit="doSomething(); return false;">
See an example live on the server
Canceling a link click
Let’s say you want to allow a user to click a link, but you don’t want that link to take the user to another page. You place “return false” to the onclick attribute:
<a href="http://wd.onepotcooking.com onclick="return false;">click me!</a>
See an example live on the server
The above code will not take the user away from the current page. They can click all they want, but they will not go anywhere.
If, in a hypothetical situation, you wanted to call a function named doSomething() first when the user clicked a link, and then cancel that link, you would do it as follows:
<a href="http://wd.onepotcooking.com" onclick="doSomething(); return false;">click me</a>
See an example live on the server
In sum…
To sum these examples up, by telling the code to “return false;” when a user clicks a link or submits a form, we tell the browser to prevent that element from performing its default behavior. We do this by placing that code in the onclick and onsubmit attributes of links and forms, respectively.
No related posts.
Leave a Reply