<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?
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
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.
You want to return false;:
$("#click").click(function(){
if($("#text").val().length < 1){
alert("click is empty!");
return false;
}
alert("ok");
});
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