Sometimes, we want to change the value of the Bootstrap 4 file input with JavaScript.
In this article, we’ll look at how to change the value of the Bootstrap 4 file input with JavaScript.
How to change the value of the Bootstrap 4 file input with JavaScript?
To change the value of the Bootstrap 4 file input with JavaScript, we can get the element with the value text and change it to the new value when a file is selected.
For instance, we write
document.querySelector(".custom-file-input").addEventListener("change", (e) => {
const fileName = document.getElementById("myInput").files[0].name;
const nextSibling = e.target.nextElementSibling;
nextSibling.innerText = fileName;
});
to listen to the change
event of the custom file input with addEventListener
.
In the change
event listener, we get the selected file’s name with
document.getElementById("myInput").files[0].name
Then we get the element with the custom file input’s value with
e.target.nextElementSibling
And we change the element’s innerText
to the fileName
to show the selected file’s name.
Conclusion
To change the value of the Bootstrap 4 file input with JavaScript, we can get the element with the value text and change it to the new value when a file is selected.