In JavaScript can I make a “click” event fire programmatically for a file input element?

前端 未结 28 1309
囚心锁ツ
囚心锁ツ 2020-11-21 06:29

I\'d like to make a click event fire on an tag programmatically.

Just calling click() doesn\'t seem to do anything or at lea

相关标签:
28条回答
  • 2020-11-21 07:07

    It works :

    For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :

    <script>
    click=function(element){
        if(element!=null){
            try {element.click();}
            catch(e) {
                var evt = document.createEvent("MouseEvents");
                evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
                element.dispatchEvent(evt);
                }
            }
        };
    </script>
    
    <input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
    
    0 讨论(0)
  • 2020-11-21 07:07

    I found that if input(file) is outside form, then firing click event invokes file dialog.

    0 讨论(0)
  • 2020-11-21 07:08

    JS Fiddle: http://jsfiddle.net/eyedean/1bw357kw/

    popFileSelector = function() {
        var el = document.getElementById("fileElem");
        if (el) {
            el.click();  
        }
    };
    
    window.popRightAway = function() {
        document.getElementById('log').innerHTML += 'I am right away!<br />';
        popFileSelector();
    };
    
    window.popWithDelay = function() {
        document.getElementById('log').innerHTML += 'I am gonna delay!<br />';
        window.setTimeout(function() {
            document.getElementById('log').innerHTML += 'I was delayed!<br />';
            popFileSelector();
        }, 1000);
    };
    <body>
      <form>
          <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />
      </form>
      <a onclick="popRightAway()" href="#">Pop Now</a>
        <br />
      <a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>
        <div id="log">Log: <br /></div>
    </body>

    0 讨论(0)
  • 2020-11-21 07:09

    THIS IS POSSIBLE: Under FF4+, Opera ?, Chrome: but:

    1. inputElement.click() should be called from user action context! (not script execution context)

    2. <input type="file" /> should be visible (inputElement.style.display !== 'none') (you can hide it with visibility or something other, but not "display" property)

    0 讨论(0)
提交回复
热议问题