Why does text change without return false

I have a simple HTML button in my form with a script like this:

$(document).ready(function () {

    $("#btn1").click(function () {
        $("#btn1").text("Button clicked");
        return false;
    });
});

With return falseit it works as I expect - I press a button and its text changes to "Button clicked". Without "return false", it changes, but then changes back.

End jQuery noob, why do I need "return false"?

+4
source share
3 answers

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

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

. , , , - ( 3 : submit, button reset).

+3

A <button> , , javascript, .

return false .

. <button> submit , , .

+5

Like @adeneo, your form submits, so the page reloads. In addition, if you do not want to use return false;, you can use preventDefault()by passing the event parameter to your function as such:

$(document).ready(function () {
    $("#btn1").click(function (ev) {
        ev.preventDefault();
        $("#btn1").text("Button clicked");
    });
});

Hope this helps,

+4
source

Source: https://habr.com/ru/post/1569777/


All Articles