How to use Anchor tag as submit button ?
The <a> (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages. Itâs either used to provide an absolute reference or a relative reference as its âhrefâ value.
Syntax:
<a href = "link"> Link Name </a>
The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. You can use href=â#topâ or href=â#â to link to the top of the current page.
To use the anchor tag as submit button, we need the help of JavaScript. To submit the form, we use JavaScript .submit() function. The function submits the form.
Syntax:
document.getElementById("GFG").submit();
Note: âGFGâ is the âidâ mentioned in the form element.
Example 1:
index.html
<!DOCTYPE html> < html > < body > < h2 >Use Anchor tag as Submit button</ h2 > < form id = "GFG" action = "submit.php" method = "POST" > Username < br /> < input type = "text" name = "UserName" id = "UserName" /> < br /> Password < br /> < input type = "password" name = "Password" id = "Password" /> < br /> < a href = "#" onclick = "myFunction()" > Click here to submit form </ a > </ form > < script > function myFunction() { document.getElementById("GFG").submit(); } </ script > </ body > </ html > |
Note: We can also call the .submit() function, by writing JavaScript as
<a href="javascript:$('GFG').submit();" >Click here to submit form</a>
Example 2:
HTML Code:
index.html
<!DOCTYPE html> < html > < body > < h1 >Use Anchor tag as Submit button</ h1 > < form id = "GFG" action = "submit.php" method = "POST" > Username < br /> < input type = "text" name = "UserName" id = "UserName" /> < br /> Password < br /> < input type = "password" name = "Password" id = "Password" /> < br /> < a href = "javascript:$('GFG').submit();" > Click here to submit form </ a > </ form > </ body > </ html > |
Output:
PHP code: The following code is the content for âsubmit.phpâ used in the above HTML code. We have to add some PHP code to send data to the database (use local server XAMPP to test the below code).
submit.php
<?php $servername = "localhost" ; $username = "root" ; $password = "" ; $dbname = "student" ; // Create connection $conn = mysqli_connect( $servername , $username , $password , $dbname ); // Check connection if (! $conn ) { die ( "Connection failed: " . mysqli_connect_error()); } $name = $_POST [ 'UserName' ]; $pwd = $_POST [ 'Password' ]; $sql = "INSERT INTO student (firstname, password) VALUES ('$name','$pwd')" ; if (mysqli_query( $conn , $sql )) { echo "New record created successfully" ; } else { echo "Error: " . $sql . "<br>" . mysqli_error( $conn ); } mysqli_close( $conn ); ?> |
Output:
-
Now, add some data in the form. Suppose Username is âAkshitâ and password is â123â
-
Now click on the hyperlink âClick here to submit formâ.
-
Let us have a look at the âstudentâ database.