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;
?
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.
When you click Call the function button, it will execute the function. To stop the function, click Stop the function execution button.
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);
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.
Try this:
$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});
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.
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.
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