Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop script with false?

<input type="text" id="text">
<span id="click">click</span>


$("#click").click(function(){

    if($("#text").val().length < 1){
       alert("click is empty!");
       false;
    }

    alert("ok");
})

LIVE: http://jsfiddle.net/2Be8a/

Why in this example if $click length == 0 i have alert click is empty (this is good) and next alert ok (not good) - why false doesnt stop script? I know - i can use else, but is possible stop with false?

like image 272
Paul Attuck Avatar asked Jul 27 '26 04:07

Paul Attuck


2 Answers

You need to use the key word return to exit the function.

$("#click").click(function(){

    if($("#text").val().length < 1){
       alert("click is empty!");
       return false; //Exits the function
    }

    //This will not execute if ($("#text").val().length < 1) == true
    alert("ok");
});

Additional Information

  • You may also want to check out the MDN docs on return.
  • As suggested in the comments, it would be "best" to add an else that returns true. Example:

    $("#click").click(function(){
    
       if($("#text").val().length < 1){
           alert("click is empty!");
           return false; //Exits the function
        }
        else {
            alert("ok");
            return true; //Exits the function
        }
    });
    

Essentially, in a jQuery handler, return true is the same as returning nothing (jQuery will take no action). return false is the equivalent of event.stopPropagation().

I suggest reading jQuery Events: Stop (Mis)Using Return False to gain a better understanding of what's really going on when you use return false.

like image 190
James Hill Avatar answered Jul 29 '26 19:07

James Hill


You want to return false;:

$("#click").click(function(){

    if($("#text").val().length < 1){
       alert("click is empty!");
       return false;
    }

    alert("ok");
});
like image 23
Michael Berkowski Avatar answered Jul 29 '26 20:07

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!