Belmark Caday
Belmark Caday

Reputation: 1683

How to check if one of the file input types has value?

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.

Upvotes: 6

Views: 6810

Answers (3)

Meligy
Meligy

Reputation: 36594

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

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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 */
    }
});

Upvotes: 7

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

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");
}

Upvotes: 1

Related Questions