Alex Rivera | Logout

jQuery: how to get "value" of file upload input field

Asked 2010-07-19T14:40:43.410
12

Is it possible to determine if the user has selected a file for a particular input type="file" field using javascript/jQuery?

I have developed a custom fieldtype for ExpressionEngine (PHP-based CMS) that lets users upload and store their files on Amazon S3, but the most popular EE hosting service has set a max_file_uploads limit of 20. I'd like to allow the user to upload 20 files, edit the entry again to add 20 more, etc. Unfortunately upon editing the entry the initial 20 files have a "replace this image" file input field that appears to be knocking out the possibility of uploading new images. I'd like to remove any unused file input fields via javascript when the form is submitted.

Edit
Report

2 Answers

2

This code will remove all the empty file inputs from the form and then submit it:

HTML:

<form action="#">
  <input type="file" name="file1" /><br />
  <input type="file" name="file2" /><br />
  <input type="file" name="file3" /><br />
  <input type="file" name="file4" /><br />
  <input type="file" name="file5" /><br />

  <input type="submit" value="Submit" />
</form>

JavaScript:

$(function() {
  $("form").submit(function(){
    $("input:file", this).filter(function(){
      return ($(this).val().length == 0);
    }).remove();
  });
});

Example: http://jsbin.com/axuka3/

answered 2010-07-19T15:08:54.437
0

This uploader has worked really well for my purposes: http://webdeveloperplus.com/jquery/ajax-multiple-file-upload-form-using-jquery/

The benefit to using it as a basis for your coding is that the files are uploaded asynchronously, so no need to limit to 20 at a time. There's a definite UI benefit to doing the upload while the user is searching.

The resize is a pretty nice feature too, if you need it!

answered 2010-07-19T14:46:30.683

Your Answer