How to submit a form with JavaScript by clicking a link?

You can submit a form with JavaScript by triggering the form’s submit event when a link is clicked.

To do this, we write:

HTML:

<form id="myForm" action="/submit" method="post">
    <!-- Your form fields go here -->
    <input type="text" name="name" placeholder="Your Name">
    <input type="email" name="email" placeholder="Your Email">
    <button type="submit" id="submitButton">Submit</button>
</form>

<!-- Link to trigger form submission -->
<a href="#" id="submitLink">Submit Form</a>

JavaScript:

// Get reference to the form and the link
const form = document.getElementById('myForm');
const submitLink = document.getElementById('submitLink');

// Add event listener to the link
submitLink.addEventListener('click', function(event) {
    // Prevent the default link behavior (navigating to a new page)
    event.preventDefault();

    // Trigger the form's submit event
    form.submit();
});

In this code, we have an HTML form with some fields and a submit button.

We also have a link with the ID submitLink that will be used to trigger the form submission.

In the JavaScript code, we get references to the form and the link.

We add an event listener to the link that listens for the click event.

When the link is clicked, the default behavior of navigating to a new page is prevented using event.preventDefault().

Then, we trigger the form’s submit event using form.submit(), which submits the form data to the server.

This way, clicking the link will submit the form without reloading the page.