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;

?

Hirvesh
  • 7,636
  • 15
  • 59
  • 72
  • Possible duplicate of [How to terminate the script in Javascript](https://stackoverflow.com/questions/550574/how-to-terminate-the-script-in-javascript) – Heretic Monkey Feb 13 '19 at 20:54

4 Answers4

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.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
5

Try this:

$('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});
turbod
  • 1,988
  • 2
  • 17
  • 31
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.

Zsub
  • 1,799
  • 2
  • 15
  • 28
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.

mczepiel
  • 711
  • 3
  • 12
  • 1
    returning false from a handler in jQuery is just a shortcut for calling event.preventDefault() and event.stopPropagation() – Zed Feb 22 '11 at 09:26
  • 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. – mczepiel Feb 28 '11 at 07:15