简体   繁体   中英

JS- Input type file firing change evt when there is no change

Hi I have been working on a script to upload files with the same input, a problem emerges when I follow the next steps:

  1. Select a file [It's uploaded as soon as change evt fires using ajax]
  2. Click select file
  3. Cancel without selecting any file

The problem is that text is alerted when I think it's not necessary

Code:

<form parameters="values...">
    <input type="file" id="file"/>
</form>

<script>
    $(document).ready(function () {
        $("#file").on("change", function () { 
            let input = this;
            if(input.files && input.files[0]) {
                //upload
            }else {
                alert("Error: Incompatible browser");
            }
        });
    });
</script>

The alert is never done unless there is no browser compatibility but this "BUG" makes the alert appear

This is a Chrome feature , where when the user clicks "Cancel" it actually clears the input from what has been set before.
IMO, a "Clear" button would have make more sense, but since the file-picking UI is the one of the OS, I guess they couldn't change it.

But anyway, your check for incompatible browsers just needs to be

// in onchange
if(input.files){

or even better

// before assigning the change handler
if('FileList' in window){

Since browsers that don't support <input type="file"> wont set neither the input.files , nor will they have the FileList constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM