admin管理员组

文章数量:1323503

I want to check wheather the user uploaded the file or not before clicking submit button through JavaScript/jQuery.

If a file is not uploaded, I don't want to allow form submission.

My html is:

<form action="/home/save" method="post" enctype="multipart/form-data" >   
    Upload Image: <input type="file" name="image" />  
    <input type="submit" value="upload" />
</form>

I want to check wheather the user uploaded the file or not before clicking submit button through JavaScript/jQuery.

If a file is not uploaded, I don't want to allow form submission.

My html is:

<form action="/home/save" method="post" enctype="multipart/form-data" >   
    Upload Image: <input type="file" name="image" />  
    <input type="submit" value="upload" />
</form>
Share edited Jun 1, 2013 at 22:22 dsgriffin 68.6k17 gold badges140 silver badges138 bronze badges asked Jun 1, 2013 at 22:19 Sarmad parvaizSarmad parvaiz 613 silver badges8 bronze badges 2
  • 3 This is actually a bad design. Why would you upload a file even the form is not plete? – batbaatar Commented Jun 1, 2013 at 22:25
  • The required attribute is not widely supported. – Ray Nicholus Commented Jun 1, 2013 at 22:36
Add a ment  | 

1 Answer 1

Reset to default 7

Using jQuery:

if(!$('input[type="file"]').val()) {
   // No file is uploaded, do not submit.
   return false;
}

jsFiddle.


Using the HTML5 required attribute (note: only supported in Chrome, Firefox, Opera, Safari 5 (on Mac) and IE10):

<input type="file" name="image" required/> 

jsFiddle.

本文标签: javascriptCheck if file is uploaded before form submissionStack Overflow