JavaScript Answers

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

Spread the love

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

To do this, we write:


<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>

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


// 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)

    // Trigger the form's submit event

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *