6

I have many of these input types:

<input type="file" name="file_upload">

And when the submit button is clicked, I want to check via JS if one these fields are not empty (in other words, there is at least one file is uploaded).

Here's my code which doesn't work:

$('#upload-button').live('click', function () {
  var has_selected_file = $('input[type=file]').val();

  if (has_selected_file) {
    /* do something here */
  }
  else {
    alert("No file selected");
  }
});

This always alerts no file selected.

3 Answers 3

7

Use .filter() to findout input element with a value, and check the length

$('#upload-button').live('click', function () {
    var has_selected_file = $('input[type=file]').filter(function(){
        return $.trim(this.value) != ''
    }).length  > 0 ;

    if (has_selected_file) {
        /* do something here */
    }
});
2
  • Thanks it worked, care to explain what is the use of filter and the return part too? Commented Sep 27, 2013 at 3:26
  • 1
    filter is a js native function which executes the specified function on every member of the object/array. Here you iterate over the collection of input[file] tags and returns an array of all elements with a selected file. If this array is non-zero in length, has_selected_file is true .. hence do something
    – jagzviruz
    Commented Sep 27, 2013 at 3:33
1

you could just do:

var has_selected_file = $.trim( $('input[type=file]').val());

if (has_selected_file != "") {
    /* do something here */
}
else {
    alert("No file selected");
}
0

Did you try to handle change instead of click?

It seems working here:

jQuery - Detecting if a file has been selected in the file input

Not the answer you're looking for? Browse other questions tagged or ask your own question.