Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

javascript - calling click event of input doesn't work in Safari

I have a input, type of file, with display:none and there is a button. after clicking the button, the input's event should be fired. In IE, Chrome and Firefox it works but not in Safari!

var elem=$('<input id="ajxAttachFiles" name="fileUpload" type="file" style="display: none;"/>');
    if($("#ajxAttachFiles").length==0){
        elem.prependTo(".ChProgress");
    }
$("#ajxAttachFiles").click();

there is no error in console. I tried this but nothing.

$(document).ready(function(){
        $("#btn").on('click',function(){
          $("#ajxAttachFiles")[0].click();
        });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input id="ajxAttachFiles" type="file" style="display:none;">
<button id="btn" type="button">Click me!</button>


   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is completely solved. The point is element of input[type=file] must not be display: none. Look at sample below:

function click(el) {
  // Simulate click on the element.
  var evt = document.createEvent('Event');
  evt.initEvent('click', true, true);
  el.dispatchEvent(evt);
}

document.querySelector('#selectFile').addEventListener('click', function(e) {
  var fileInput = document.querySelector('#inputFile');
  //click(fileInput); // Simulate the click with a custom event.
  fileInput.click(); // Or, use the native click() of the file input.
}, false);
<input id="inputFile" type="file" name="file" style="visibility:hidden; width:0; height:0">
<button id="selectFile">Select</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...