Sometimes, we want to submit a form with JavaScript by clicking a link.
In this article, we’ll look at how to submit a form with JavaScript by clicking a link.
How to submit a form with JavaScript by clicking a link?
To submit a form with JavaScript by clicking a link, we can listen to the click event of the button.
For instance, we write
<form id="form-id">
<button id="your-id">submit</button>
</form>
to add a form.
Then we write
const form = document.getElementById("form-id");
document.getElementById("your-id").addEventListener("click", () => {
form.submit();
});
to select the form
with getElementById
.
Then we select the button with
document.getElementById("your-id")
And then we call addEventListener
to add a click event listener to the button.
In the click event handler callback, we call form.submit
to submit the form.
Conclusion
To submit a form with JavaScript by clicking a link, we can listen to the click event of the button.