user3080627
user3080627

Reputation: 5

Submit form only if file is selected

Hey there in my jquery i am checking "on submit", if file is selected or not:

$(document).ready(function(){
  $("form").submit(function(){
    var fileName = $("#picture-field").val();

    if(fileName) { // returns true if the string is not empty
        alert(fileName + " was selected");
    } else { // no file was selected
        alert("no file selected");
    }
  });
});

If no file is selected, it displays: "no file selected", but then the form is sbumitted.

But i want that the form can only be submitted if a file is selected.

If no file selected and the user presses "submit", e.g. display: "please select file".

Upvotes: 0

Views: 1557

Answers (3)

Wilfredo P
Wilfredo P

Reputation: 4076

only add return false after the alert(), This will cancel the submit.

$(document).ready(function(){
  $("form").submit(function(){
    var fileName = $("#picture-field").val();

    if(fileName) { // returns true if the string is not empty
        alert(fileName + " was selected");
    } else { // no file was selected
        alert("no file selected");
        return false; //<---- Add this line.
    }
  });
});

Upvotes: 3

ramchauhan
ramchauhan

Reputation: 248

$(document).ready(function(){
  $("form").submit(function(){
    var fileName = $("#picture-field").val();

    if(fileName) { 
       alert(fileName + " was selected");
    } else { // no file was selected
       alert("no file selected");
       return false; 
    }
 });
});

simply use return false

Upvotes: 0

A.T.
A.T.

Reputation: 26382

simply add return false, when you don't want to submit form. This will stop click event propagation.

$(document).ready(function(){
  $("form").submit(function(){
    var fileName = $("#picture-field").val();

    if(fileName) { // returns true if the string is not empty
        alert(fileName + " was selected");
    } else { // no file was selected
        alert("no file selected");
        return false;
    }
  });
});

Upvotes: 0

Related Questions