Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox fires on choose, not on change

Consider this:

<input type="file" id="filePicker">
<script>
    document.getElementById('filePicker').onchange = function() {
        alert('Hi!');
    };
</script>

Even if you choose the same file and the filePicker value doesn't change, you'll see the alert box in Firefox. Any solutions?

like image 589
Mori Avatar asked Oct 18 '22 20:10

Mori


2 Answers

Use a temporary variable to hold the name of the filename that you can check the next time you select a file:

var filenameTemp = null;
document.getElementById('filePicker').onchange = function(e) {
  var filename = e.target.value;
  if (filename !== filenameTemp) {
    filenameTemp = filename;
    console.log('OK');
    // other code
  } else {
    console.log('Not OK')
  }
};

DEMO

like image 186
Andy Avatar answered Oct 21 '22 17:10

Andy


Run the snippet below. It will say "New File!" when there is a new file for both Chrome and Firefox.

var previousFile = {};

function isSame(oldFile, newFile) {
  return oldFile.lastModified === newFile.lastModified &&
    oldFile.name === newFile.name &&
    oldFile.size === newFile.size &&
    oldFile.type === newFile.type;
} 

document.getElementById('filePicker').onchange = function () {
  var currentFile = this.files[0];
  
  if (isSame(previousFile, currentFile) === false) {
    alert('New File!');
    previousFile = currentFile;
  }
};
<input type="file" id="filePicker">
like image 34
boombox Avatar answered Oct 21 '22 17:10

boombox