i have an input type file on a wall post script for my site. i am trying to hide the input field when the form box is opened and closed with no file selected.
$(".file-upload").show().click();
i tried using jquery change event, however that only get triggered when a file is selected, and i want to be able to detect an empty return
$(".file-upload").show().click().change(function(){
// this is only triggered when a file is here
$(this).hide();
});
Update:
$(".file-upload").show().click();
$(".file-upload").change(function(){
$(this).hide(); // only if .file-upload is empty
});
i want this to trigger when a user clicks on the file input, and when the dialog opens and they don't select anything, i want to hide the file input box again.
OK, the Fiddle you added clarified your question considerably.
Essentially what you're looking for is a callback function to run when the file input dialog closes. Unfortunately, there is no standard browser implementation of a file upload API that would help you with this. However, based on this specific use case, I think there's a work-around.
The change
event on a file upload input will only run if the value actually changes, not every time the dialog is opened and closed. So in the code you have now, the change event never fires because the value of the input never actually changes, it just stays empty. So if you move your code to show the input out of the click
handler for the button and into the change
handler for the file input, you can achieve the functionality you're looking for.
$('button').click(function () {
$(".file-upload").click();
});
// if the dialog returns a file, then show the file input field
$(".file-upload").on('change', function (e) {
if (e.target.files.length) {
$(this).show();
} else {
$(this).hide();
}
});
Really, the else
block in there shouldn't be necessary, but I guess it's theoretically possible for someone to add a file and then remove it (I don't know if this is even supported functionality in most browsers), and the else
block here covers that case.