Sometimes, we want to submit a file input without submit button using JavaScript.
In this article, we’ll look at how to submit a file input without submit button using JavaScript.
How to submit a file input without submit button using JavaScript?
To submit a file input without submit button using JavaScript, we can call the form element’s submit
method.
For instance, we write:
<form enctype="multipart/form-data" method="POST" action="/upload">
<input id="fileInput" type="file" name="file">
<input type="submit">
</form>
to add a form.
Then we write:
const fileInput = document.getElementById('fileInput')
const form = document.querySelector('form')
fileInput.addEventListener('change', () => {
form.submit();
});
to select the file input and form with document.getElementById
and document.querySelector
respectivelt.
Next, we call fileInput.addEventListener
to add a change listener to the file input.
In the change listener, we call form.submit
to submit the form.
Now when we select a file, the form submission will be done immediately.
Conclusion
To submit a file input without submit button using JavaScript, we can call the form element’s submit
method.