Home >Web Front-end >JS Tutorial >How Can I Automatically Populate an Input File's Value Using Drag and Drop?
How to Automatically Populate Input File Value When Dragging and Dropping on Page
Background:
For security reasons, it was previously not possible to programmatically set the value of input files using JavaScript. However, with advancements in browser technology, this has changed.
Solution:
Step 1: Enable File Drop
Add drag and drop event listeners to the desired container:
const target = document.getElementById("container"); target.addEventListener("dragover", (e) => { e.preventDefault(); target.classList.add("dragging"); }); target.addEventListener("dragleave", () => { target.classList.remove("dragging"); });
Step 2: Assign File Value
Capture the FileList object from the dataTransfer event:
target.addEventListener("drop", (e) => { e.preventDefault(); target.classList.remove("dragging"); const files = e.dataTransfer.files; document.getElementById("file-input").files = files; });
Replace "container" with the ID of the container element you want to enable drag and drop on, and "file-input" with the ID of the input file element.
Note:
This method works on modern browsers that support the specification.
The above is the detailed content of How Can I Automatically Populate an Input File's Value Using Drag and Drop?. For more information, please follow other related articles on the PHP Chinese website!