Friday, November 14, 2025
HomeLanguagesJavascriptHow to submit a form by clicking a link in JavaScript ?

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

In this article, we have submitted a form using JavaScript by clicking a link. In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked. When we click on the link, the function submitForm() will get executed. This function will get the element object using DOM getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method.

Example: Create a form and submit it using the above approach. It is required for the form structure where the user will provide his/her details.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h2 style="color:green">neveropen</h2>
    <b>Submit form details</b>
 
    <form id="form__submit" action="form.php" method="post">
        <label>NAME: </label><br />
        <input type="text" name="name" /><br />
        <label>AGE: </label><br />
        <input type="number" name="age" /><br />
        <label>CITY: </label><br />
        <input type="text" name="city" /><br /><br />
        <a href="#" onclick="submitForm()">Submit Here</a>
    </form>
 
    <script>
        function submitForm() {
            let form = document.getElementById("form__submit");
            form.submit();
        }
    </script>
</body>
 
</html>


Note: The given HTML code will redirect the form data to the site or file which is mentioned in the action attribute.

PHP Code: Create a PHP file to get the user entered form data, rename this PHP file as “form.php”. This code displays the user form data.

PHP




<?php
    $name=$_POST['name'];
    $age=$_POST['age'];
    $city=$_POST['city'];
 
    echo "NAME-SUBMITTED : $name <br>";
 
    echo "AGE-SUBMITTED :  $age <br>";
 
    echo "CITY-SUBMITTED:  $city";
?>


Output:

user form data

PHP is a server-side language. So it requires a server. Please refer PHP tutorial for a better understanding.

RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7143 POSTS0 COMMENTS
Thapelo Manthata
6838 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS