I have a form that, when submitted, I need to do some additional processing before it should submit the form. I can prevent default form submission behavior, then do my addi
When you bind the .submit()
event to the form, and you do the things you want to do before returning (true), these things happen prior to the actual submission.
For example:
$('form').submit(function(){
alert('I do something before the actual submission');
return true;
});
Simple example
Another example on jquery.com: http://api.jquery.com/submit/#entry-examples
This is, IMHO, the most generic and robust solution (if your actions are user-triggered, eg 'user clicks on a button'):
As an example, note this elegant solution to adding "Are you sure?" popup to any button just by decorating a button with an attribute. We will conditionally continue default behavior if the user doesn't opt out.
1. Let's add to every button that we want an "are you sure" popup a warning text:
<button class="btn btn-success-outline float-right" type="submit" ays_text="You will lose any unsaved changes... Do you want to continue?" >Do something dangerous</button>
2. Attach handlers to ALL such buttons:
$('button[ays_text]').click(function (e, from) {
if (from == null) { // user clicked it!
var btn = $(this);
e.preventDefault();
if (confirm() == true) {
btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
}
}
// otherwise - do nothing, ie continue default
});
That's it.
Using this way You will do a endless Loop on Your JS. to do a better way you can use the following
var on_submit_function = function(evt){
evt.preventDefault(); //The form wouln't be submitted Yet.
(...yourcode...)
$(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
$(this).submit();
}
$('form').on('submit', on_submit_function); //Registering on submit.
I hope it helps! Thanks!
You can use e.preventDefault()
which will stop the current operation.
than you can do$("#form").submit();
$('#form').submit(function (e)
{
return !!e.submit;
});
if(blabla...)
{...
}
else
{
$('#form').submit(
{
submit: true
});
}