Reputation: 755
I have a file input box that allows a user to select a file from their local filesystem. This file is then read into a textarea. I'm aware that on-change events will only happen once the input field is no longer in focus. However, the behavior of my application is inconsistent. Sometimes the input loses focus correctly after the user selects a file and sometimes it does not. I don't know how to force the input to lose focus after the user has selected a file. My code:
HTML:
<div class="form-group pull-left">
<input type="file" id="scriptFile" class="form-control input-sm inputfile">
<label for="scriptFile"><div class="glyphicon glyphicon-open"></div><span> Choose a Script…</span></label>
</div>
Main.js:
$("#scriptFile").change(function(event) {
var file = event.target.files[0];
// Just updates the "select a file" button to display the selected file's name.
$("#scriptFile").next('label').find('span').html(" " + event.target.value.split( '\\' ).pop());
var reader = new FileReader();
reader.onload = function(event) {
editor.setValue(event.target.result);
editor.clearSelection();
};
reader.readAsText(file);
$('#scriptFile').addClass("selected"); //CSS purposes
editor.focus();
});
How do I ensure that after a user selects a file from their local system that focus is removed from the input to properly trigger the change event?
UPDATE: The issue has to do with selecting the same file, not focus. The file input still has the old file value...and since it's not a change, the change event is not being triggered. So, now I need to find out how to clear the file input value using jQuery.
UPDATE: Solved! Needed to add this to change event to clear value:
$('#scriptFile').closest('form').get(0).reset();
Upvotes: 2
Views: 834
Reputation: 755
The on change event is not being triggered because if the file input value is not being cleared and the user selects the same file again, no change has occurred. After reading in the file, clear the file input value using:
$('#scriptFile').closest('form').get(0).reset();
This will ensure that if the user selects the same file again, the on change event will trigger as the value has now been reset.
Upvotes: 2