March 9, 2012

Hide the upload submit button if field "file" is empty

Question by Warface

With this simple example

<form action="" method="post" enctype="multipart/form-data">
            Upload images: <input type="file" name="images[]" multiple="multiple"> <input type="submit" name="submitImgs" value="Upload"/>
        </form>

How can I hide the submit button until somthing’s in the file field, I’ve tried to make a php script that look if the $_FILES[‘error’] == 4 or is_file_uploaded, etc and that don’t work. So I want to simply hide the button until something is selected in the file field.

The answer could be in javascript, jQuery… I don’t care 😀

Thanks

Answer by Rob W

The <input type="file"> element has a files property.

Simply check files.length.

jQuery example, which modifies the submit button on the fly:

// Select the <input type="file"> element
$('input[type=file][name="images[]"]').change(function(){
    var hasNoFiles = this.files.length == 0;
    $(this).closest('form') /* Select the form element */
       .find('input[type=submit]') /* Get the submit button */
       .prop('disabled', hasNoFiles); /* Disable the button. */
});

Answer by Starx

Use this. Attach the code on the change event of the file field.

  $(function() {
     $("input:file").change(function() {
       var fileName = $(this).val();
       if(filename != "") { $("#submitButtonId").show(); } //show the button
     });
  });

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!