And when t...">

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

I have many input types like this:

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

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

Here is my code that does not 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 warns that no file is selected.

+6
source share
3 answers

Use .filter () to find an 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 */ } }); 
+7
source

you can just do:

 var has_selected_file = $.trim( $('input[type=file]').val()); if (has_selected_file != "") { /* do something here */ } else { alert("No file selected"); } 
+1
source

Have you tried handling change instead of click ?

Seems to work here:

jQuery - detect if file was selected in input file

0
source

Source: https://habr.com/ru/post/954742/


All Articles