<div class="selected-file-container align-items-center justify-content-between d-none">
<div class="selected-file d-flex align-items-center">
<img id="selectedImage" class="hidden" src="" alt="Selected Image"/>
<span id="selectedFileName">Filename.jpg</span>
</div>
<span>1 MB</span>
</div>
<input type="file" id="fileInput" style="display: none" />
<label for="fileInput" class="choose-file-btn">
<span>Choose File</span>
</label>
Creating an image selection button using HTML and Bootstrap along with the ability to show an icon next to the selected image name.
<script>
document.getElementById("fileInput").addEventListener("change", function (event) {
const selectedFile = event.target.files[0];
const selectedImageElement = document.getElementById("selectedImage");
const selectedFileNameElement = document.getElementById("selectedFileName");
const selectedFileContainer = document.querySelector(".selected-file-container");
if (selectedFile) {
const imageIconElement = document.createElement("i");
imageIconElement.className = "fa-regular fa-image";
selectedFileNameElement.innerHTML = "";
selectedFileNameElement.appendChild(imageIconElement);
selectedFileNameElement.insertAdjacentHTML("beforeend", selectedFile.name);
selectedImageElement.src = URL.createObjectURL(selectedFile);
selectedFileContainer.classList.remove("d-none");
selectedFileContainer.classList.add("d-flex");
} else {
// Hide selected-file-container if no file is selected
selectedFileContainer.classList.remove("d-flex");
selectedFileContainer.classList.add("d-none");
}
});
</script>
The script involves selecting an image, adding an image icon to the selectedFileContainer
, displaying only the selected image name, not the image itself.
The desired functionality is when a new image is selected, it should be listed below the previous image in separate selected-file-containers. Each new selection adds a new container under the existing list of images, creating a block layout above the button.
https://i.sstatic.net/sppTC.png
https://i.sstatic.net/AwLRJ.png
Currently, when different images are selected, only the name changes within the same container. The goal is to display each selected image name in individual containers stacked vertically one after the other.