简体   繁体   中英

Dialog open in Javascript function don't allow selection of file

I have this button in my page:

        <button type="button" class="btn btn-secondary" onclick="edit_arquivo(event,this);">
          <i class="far fa-edit"></i>
        </button>

with a Javascript function associated to it, where I want open a dialog to choose a file to upload to the server after. I have this code to open the dialog:

  var input = document.createElement("input");
  input.type="file";
  input.click();

which works for opening the dialog, but also I notice that after that, the code keeps being executed or something, and in the next part:

var file = input.files[0];
let name = file.name.split('.')[0] + '_' + (type=='versaoPaga'? 'pro' : 'lite');
let ext = file.name.split('.').pop();

I got an error, because input.files[0] is returning undefined, since I do not have time to select a file in the dialog in the screen (even if I select and click ok, doesn't matter anymore, no action is executed after that error).

To try avoid that, I also try:

  var input = document.createElement("input");
  input.type="file";
  input.addEventListener("click", function(evt) {
    evt.stopPropagation();
    evt.stopImmediatePropagation();
  });
  input.click();

which give me the same result.

Anyone can give a hint about the right way to accomplish what I want?

...but also I notice that after that, the code keeps being executed or something...

Yes, it does. Calling click doesn't stop the JavaScript code and make it wait for the user to pick a file. Web development is all about responding to events . In this case, the event is the user picking a file:

var input = document.createElement("input");
input.type="file";
input.addEventListener("change", function() {
    var file = input.files[0];
    let name = file.name.split('.')[0] + '_' + (type=='versaoPaga'? 'pro' : 'lite');
    let ext = file.name.split('.').pop();
});
input.click();

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