Cancel event on input type=“file”

前端 未结 4 1429
北恋
北恋 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条回答
  •  温柔的废话
    2020-12-03 07:47

    When we select the file following events are called -

    Scenario 1 : When the select file is clicked and then cancel is clicked

    Focus event value=""

    Click event value=""

    Blur event value=""

    Focus event value=""

    Blur event value="" (when the user clicks somewhere out)

    Scenario 2 : When the file is selected -

    Focus event value=""

    Click event value=""

    Blur event value=""

    Focus event value=""

    Change event value="filevalue"

    Blur event value="filevalue"

    Focus event value="filevalue"

    Blur event value="filevalue" (when the user clicks somewhere out)

    We see here, when the Blur event (last event) is called after focus event with no value of file means that the Cancel button is clicked.

    My scenario was to change the Submit button text to "Please wait" while the file is loading currentEvent variable is used to hold the current event value either click or focus if the currentEvent = focus and file value is null means Cancel button is clicked.

    Javascript
    
    var currentEvent = "focus";
    
    function onFileBrowse() {    
        var vtbFile = $('#uploadFile')[0].files[0];
    
        if (vtbFile != undefined) {
            var extension = vtbFile.name.split('.').pop().toLowerCase();
            var valError = "";
    
            if (extension === 'xlsx' || extension === 'xlsb' || extension === 'csv') {
                if (vtbFile.size === 0)
                    valError = "File '" + vtbFile.name + "' is empty";
            }
            else
                valError = "Extension '" + extension + "' is not supported.";
    
            if (valError !== "") {            
                alert("There was an issue validating the file. " + valError, 20000);
            }        
        }
        //hide Indicator
        var buttonUpload = document.getElementById('btnUploadTB');
        buttonUpload.innerText = "Submit";
    };
    
    
    function fileClick() {
        //show Indicator
        var buttonUpload = document.getElementById('btnUploadTB');
        buttonUpload.innerText = "Please wait..";
        
        document.getElementById('uploadFile').value = null;   
        currentEvent = "click";
    }
    function fileFocus() {
        currentEvent = "focus";
    }
    
    function fileBlur() {
        
        if (!document.getElementById('uploadFile').value && currentEvent == "focus") {
            console.log('blur' + 'change to submit');
            //hide Indicator
            var buttonUpload = document.getElementById('btnUploadTB');
            buttonUpload.innerText = "Submit";
        }
    }
    HTML
    
    
    
    

提交回复
热议问题