How to disable submit button until file is selected

10,251

Solution 1

This jQuery should work, and is tied to the file input's change() event. This code also applies the disabled attribute so, in the event the user has JavaScript disabled, it shouldn't prevent the form being used:

$(document).ready(
    function(){
        $('input:submit').attr('disabled',true);
        $('input:file').change(
            function(){
                if ($(this).val()){
                    $('input:submit').removeAttr('disabled'); 
                }
                else {
                    $('input:submit').attr('disabled',true);
                }
            });
    });

JS Fiddle demo.

Solution 2

A simpler way is to check the file field when the user actually submits the form... that way you won't have to look for form changes.

$(function() {
   $('form').submit(function() {
      if(!$("form input[type=file]").val()) {
         alert('You must select a file!');
         return false;
      }
   });
});

This code is Unobtrusive JavaScript and it won't mess up the form if the user does not support JS.

Share:
10,251
at.
Author by

at.

Updated on June 04, 2022

Comments

  • at.
    at. almost 2 years

    I have an HTML file upload page and I need the submit button to be disabled until a file is selected. Then the submit button will be enabled and the user can upload. I assume I can use jQuery code to query the file upload field's value to see whether a file has been selected to upload. And I assume I can check that whenever focus has left the file upload field. My concern is that some browsers might act funny with this and then my users can't upload any files.

    Is there a safe way to do this, preferably using jQuery, where I won't be in danger of having some users unable to upload?