http://encosia.com/button-click-handlers-ajax-premature-submission
Excerpts:
Excerpts:
Clicking the button did run our JavaScript code, which we can verify by seeing that the request began. However, it also triggered a form submission since that’s the browser’s default behavior when buttons inside forms are clicked.
...
Putting a leash on the browser’s default behavior
There are a couple ways to tame the browser’s form submission mechanism and make the button work asynchronously, as expected.
- return false – In almost all cases, an event handler function returning false causes the browser to cancel any subsequent behaviors that the event would normally have triggered (like submitting a form). Using return false works, but you need to be careful about where you place it since the return statement can abort your code early and it can have unintended side-effects.
Since
- preventDefault() – The browser sends an event parameters to handlers, which details information about the action that triggered the handler. That event object also exposes a method that prevents the browser’s default reaction to that event:
preventDefault()
. For click handlers on submit buttons inside forms, that includes preventing the form submission.return false
does have the issue of sometimes breaking other code and plugins when it stops propagation, I usepreventDefault()
by… default.
No comments:
Post a Comment