Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

?

like image 549
Hirvesh Avatar asked Feb 22 '11 08:02

Hirvesh


People also ask

How do I stop JavaScript from running?

Press Control+Shift+P or Command+Shift+P (Mac) to open the Command Menu. Start typing javascript , select Disable JavaScript, and then press Enter to run the command. JavaScript is now disabled.

How do you stop a function from running?

When you click Call the function button, it will execute the function. To stop the function, click Stop the function execution button.

How do I stop a jQuery script?

The stop() method is an inbuilt method in jQuery which is used to stop the currently running animations for the selected element. Syntax: $(selector). stop(stopAll, goToEnd);


4 Answers

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.

like image 119
David Hedlund Avatar answered Sep 29 '22 10:09

David Hedlund


Try this:

$('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});
like image 27
turbod Avatar answered Sep 29 '22 09:09

turbod


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.

like image 22
Zsub Avatar answered Sep 29 '22 09:09

Zsub


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.

like image 29
mczepiel Avatar answered Sep 29 '22 10:09

mczepiel