Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the text change back without 'return false'

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

like image 929
ChrisA Avatar asked Dec 15 '22 17:12

ChrisA


2 Answers

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 image 188
adeneo Avatar answered Jan 04 '23 06:01

adeneo


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,

like image 44
cram2208 Avatar answered Jan 04 '23 06:01

cram2208