Mori
Mori

Reputation: 6780

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?

Upvotes: 5

Views: 61

Answers (2)

boombox
boombox

Reputation: 2456

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">

Upvotes: 1

Andy
Andy

Reputation: 63524

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

Upvotes: 2

Related Questions