1

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}" class="file-upload btn btn-secondary">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: ....

Gerard
  • 15,418
  • 5
  • 30
  • 52
xtlc
  • 1,070
  • 1
  • 15
  • 41
  • 3
    `change` events are fired on `input` elements, not on their labels. (Or on buttons, although your "button" is in fact a label rather than a button.) – Robin Zigmond Jan 03 '22 at 19:43

1 Answers1

1

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}" class="file-upload btn btn-secondary">
  <input type="file">upload file</input></label>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79