Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 651
Belmark Caday Avatar asked Sep 27 '13 03:09

Belmark Caday


People also ask

How do I check if an input type is empty?

If element. files. length property returns 0 then the file is not selected otherwise file is selected.

Does input type file have value attribute?

A file input's value attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the value is an empty string ( "" ). When the user selected multiple files, the value represents the first file in the list of files they selected.

How do you assign the value of an input type file?

In HTML, we will use the type attribute to take input in a form and when we have to take the file as an input, the file value of the type attribute allows us to define an element for the file uploads.

How can we check input type is not empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.


1 Answers

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 */
    }
});
like image 78
Arun P Johny Avatar answered Nov 15 '22 11:11

Arun P Johny