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.
If element. files. length property returns 0 then the file is not selected otherwise file is selected.
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.
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.
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.
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 */
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With