Hirvesh
Hirvesh

Reputation: 7982

Stop JavaScript script execution

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;

?

Upvotes: 15

Views: 86273

Answers (4)

mczepiel
mczepiel

Reputation: 711

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.

Upvotes: 1

Zsub
Zsub

Reputation: 1797

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.

Upvotes: 1

turbod
turbod

Reputation: 1988

Try this:

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

Upvotes: 5

David Hedlund
David Hedlund

Reputation: 129792

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.

Upvotes: 31

Related Questions