4

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'?

Travis J
  • 81,153
  • 41
  • 202
  • 273
ChrisA
  • 4,163
  • 5
  • 28
  • 44

3 Answers3

5

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • :blush:, as you can tell, it's not just JQuery I'm a bit of a noob with. That's great, thank you. I've put a
    in that shows the time when the page loads, and indeed it does update when I click when there's no return false.
    – ChrisA Jan 02 '15 at 22:57
4

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,

cram2208
  • 416
  • 6
  • 14
3

If the <button> was not intended to submit the form, then instead of using return false; or other workarounds make the button the proper type.

<button id="btn1" type="button">

And it will stop submitting when clicked. The reason it does now is because the button's default type is submit (it has 3 possible types: submit, button, and reset).

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273