The following is what I'd like to do in my JQuery script. In the submit function (4th) below, I want to decide if the form has file input and submit with either ajax or just a regular form submit without ajax. In other words, if the form has upload, do a regular submit.
I wrote the question in the submit function below. That is the only thing I need to make it work.
Thank you!
function FindFileInput(){
// check for file input
var FileInput = $('input:file');
if(FileInput.length > 0){
return true;
}else{
return false;
}
}
function validation(){
// code to validate form
...
}
function ajaxSubmit(formData){
$.ajax({
// ajax submit code
});
}
$(myForm).submit(function(e){
e.preventDefault();
// 1. if NO file input present
if(FindFileInput() === false){
if(validation() === true){
// serialize and call ajaxSubmit function
}
}
// 2. if file input IS present
if(FindFileInput() === true){
if(validation() === true){
// QUESTION: How do I submit the form here???
}
}
});
If you want the submit to continue just don't prevent the default behavior and return true.
Don't call the
e.preventDefault()
so early, do it only when you actually want to stop the form from being posted the default way (thus, when a file is selected). That way you can get rid of the second if-statement, and just let the submit JS-function do nothing when there is a file to send. That way the form will be sent the default way, if no file is selected.Simple! I removed e.preventDefault(); and added some else conditions. However I provided a very procedural (less ideal) solution.
this.submit()
provided that you haven't overridden it with something like<input name="submit" />
demo:
http://jsfiddle.net/4buHP/
The native
.submit()
doesn't fire the jQuery event.From http://api.jquery.com/submit/:
So turn your logic around. Don't call e.preventDefault() as default and then try to undo it, but rather only call it when it is actually needed.