I have a PHP form with a file input field, and two text input fields. What I want to do is use jQuery to check if the file input field is empty, and if it's not, then show a specific div, but the following code does not work:
<input type="file" name="blog-entry-image" id="blog-entry-image" />
var fileInput = $.trim($("#blog-entry-image").val());
if (fileInput.length > 0) {
$("#new-blogentry").click(function() {
$("#sending").show();
return true;
});
}
"new-blogentry" is the submit button, and "sending" is a div with an animated gif.
<input type="file" name="blog-entry-image" id="blog-entry-image" />
$(document).ready(function (){
$("#blog-entry").click(function() {
var fileInput = $.trim($("#blog-entry-image").val());
if (fileInput && fileInput !== '') {
$("#sending").show();
return true;
}
});
});
Change fileInput.length > 0
to
fileInput != "" && fileInput.trim() != ""
You have things backwards. You need to get the file input value after the user clicks.
$('#new-blogentry').click(function() {
var fileInput = $.trim($("#blog-entry-image").val());
if (fileinput.length > 0) {
...
}
});
if($('#new-blogentry').val()==''))
is enough to check if the file input is empty
I suggest you to use jquery validator plugin for all frontend based validation http://jqueryvalidation.org/