Home > Enterprise >  onclick recognized, but onchange not
onclick recognized, but onchange not

Time:01-04

I probably stared to long at it - problem is smilar to this.I added an event listener to a button, but only the onclick method fires something. I want to display the name of the selected file from an upload:

var ulButtons = document.getElementsByClassName("file-upload");
[...ulButtons].forEach(ulButton => {
  ulButton.addEventListener("click", function() {
    ulButton.value = null;
    console.log("this works")
  })
});


[...ulButtons].forEach(ulButton => {
  ulButton.addEventListener("change", function() {
    console.log("changed to:", this.value)
  })
});
<label for="{field.id_for_label}" >upload file</label>

I fail to see why clicking on the upload button always shows in the console, but selecting a file does not trigger the changed to: ....

CodePudding user response:

Your code would work if you inlcude input field with type file.

var ulButtons = document.getElementsByClassName("file-upload");
[...ulButtons].forEach(ulButton => {
  ulButton.addEventListener("click", function() {
    ulButton.value = null;
    console.log("this works")
  })
});


[...ulButtons].forEach(ulButton => {
  ulButton.addEventListener("change", function() {
    console.log("changed to:", this.value)
  })
});
<label for="{field.id_for_label}" >
  <input type="file">upload file</input></label>

  •  Tags:  
  • Related