Sometimes, we want to auto-submit an upload form when a file is selected with JavaScript.
In this article, we’ll look at how to auto-submit an upload form when a file is selected with JavaScript.
How to auto-submit an upload form when a file is selected with JavaScript?
To auto-submit an upload form when a file is selected with JavaScript, we can listen for the change event triggered by the file input.
And we call the form’s submit
method when the change event of the file input is emitted.
For instance, we write
<form action="http://example.com">
<input type="file" />
</form>
to add the form with the file input.
Then we write
const form = document.querySelector("form");
const input = document.querySelector("input");
input.onchange = () => {
form.submit();
};
to select the form and input with querySelector
.
And we set the input.onchange
property to a function that calls form.submit
to submit the form when the file selection is changed.
Conclusion
To auto-submit an upload form when a file is selected with JavaScript, we can listen for the change event triggered by the file input.
And we call the form’s submit
method when the change event of the file input is emitted.