Cancel event on input type=“file”

前端 未结 4 1432
北恋
北恋 2020-12-03 06:56

I am working with a standard file input for uploads, and I am looking for a way to attach a function to an event when the user clicks/hits enter on the \"cancel\" button (or

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 07:35

    I had the problem where I clicked the cancel button on the input type="file" element and wanted the function to do nothing. if something was selected and I clicked the open button then I wanted my function to do something. The example only shows the method, I stripped out what I do with it after it opens. I put in the alerts just so you could see there isn't a filename coming back from the dialog when cancel is clicked. Here is a method I use, it is simple but it works.

     function openFileOnClick(){
        document.getElementById("fileSelector").value = "";
        document.getElementById("fileSelector").files.length = 0;            
        document.getElementById("fileSelector").click();
        if(document.getElementById("fileSelector").files.length >= 1){
            alert(document.getElementById("fileSelector").value);
            //Do something 
        }
        else{
            alert(document.getElementById("fileSelector").value);
            //Cancel button has been called.
        }
    }
    
    
    
    
    
    
    
    

提交回复
热议问题