javascript tutorial - [Solved-5 Solutions] How to prevent buttons from submitting forms - javascript - java script - javascript array
Problem:
How to prevent buttons from submitting forms
Solution 1:
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button So we need to specify its type explicitly:
in order to override the default submit type. we just want to point out the reason why this happens =)
Solution 2:
Set the type on our buttons:
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix our removeItem() function so that it doesn't trigger an exception:
- Note the change: our original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
- FWIW, there's another way we could go with this... Wire up our event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
- This technique keeps all of our logic in one place, making it easier to debug... it also allows we to implement a fall-back by changing the
type
on the buttons back tosubmit
and handling the event server-side - this is known as unobtrusive JavaScript
Solution 3:
We agree with Shog9, though we might instead use:
According to wikitechy, the <button> tag has different behavior on different browsers.
Solution 4:
Suppose our HTML form has id="form_id"
Add this jQuery snippet to our code to see result,
Solution 5:
This is an html5 error like has been said, we can still have the button as a submit (if we want to cover both javascript and non javascript users) using it like:
This way we will cancel the submit but still do whatever we are doing in jquery or javascript function`s and do the submit for users who dont have javascript.