15

I have a form which is being submitted by ajax. Before submission, there's a function which checks if a textarea in the form is empty before submitting. if it is empty, I need to stop the script and show a modal box AND prevent the submission of data to proceed.

How do I stop execution? Do I use

break;

?

1

4 Answers 4

31

Nope, you generally use return;

Of course the exact details will vary depending on your implementation. You may need to return false;, for instance, and manually check the return value to see whether or not to keep executing script in the calling function.

Sign up to request clarification or add additional context in comments.

3 Comments

return false; it is. Thanks!
what if it is inside Loop ? return false doesn't work then ??
@simmisimmi: return false will break out of a function even if you're inside a for loop.
5

Try this:

$('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

Comments

1

You could use break; but if you do you can't check return values (use return; or return $bool; for that).

I think a construction like this would do:

.submit(function ()
{
    if (verifyInput())
    {
    // continue
    }
    else
    {
    // show user there is something wrong
    }
});

verifyInput() in this case would return a boolean, of course, representing wether or not the form was properly filled.

Comments

1

While returning works well enough to prevent the default submit action, I would suggest calling event.preventDefault(). Simply call it first thing to prevent the user agent's default handling of that eventType. It's arguably the more modern way of doing this.

This of course assumes you have a reference to the event, which will be the first argument to your handler function or your EventListener object's handleEvent method so long as you provide a parameter for it.

It's just another tool to have in your toolbox, it also pairs nicely with event.stopPropagation, for when you don't want to stop the default but just want to stop event distribution.

2 Comments

returning false from a handler in jQuery is just a shortcut for calling event.preventDefault() and event.stopPropagation()
Sure, but it does have the side effect of also stopping propagation well. If you just want to stop the default submission of the form I think it's more correct to use preventDefault. Unless you also want to not give other listeners a chance to realize the event happened.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.