I have a simple HTML button on my form, with script as follows:
$(document).ready(function () {
$("#btn1").click(function () {
$("#btn1").text("Button clicked");
return false;
});
});
With the return false
, it works as I expect - I click the button, and its text changes to 'Button clicked'. Without the 'return false', it changes, but then changes back.
Complete JQuery noob here, why do I need the 'return false'?
A <button>
in a form submits the form, which is why it turns back, the page reloads resetting everything javascript changed, so you see the change, and it immediately reloads the page when the form submits.
The return false
prevents the form from submitting when clicking the button.
Note: the <button>
element has a default type of submit
, so it will always submit the form it's nested inside.
Like @adeneo said, your form is being sent out so the page will reload. Additionally, if you don't want to use return false;
you can use preventDefault()
by passing an event parameter to your function as such:
$(document).ready(function () {
$("#btn1").click(function (ev) {
ev.preventDefault();
$("#btn1").text("Button clicked");
});
});
Hope this helps,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With