In JavasCript we have many built in methods one of them in submit(); using submit method we can submit any form on any action. Let’s say we have a form which takes name, email, and message but we dont want to submit this form using submit button we want to submit this form using a text anchor link we can do that using javaScript so if we want to submit a form using anchor link a href we can give an id to our form and then we can create a javaScript function to submit form by its id and we can call that function onclick of anchor link.
Example submit form JavaScript
[code lang=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
//Function to submit form by its id..
function submit_form() {
document.getElementById(‘my_form’).submit();
}
</script>
</head>
<body>
<div id="sum"><!–javaSCript will calculate here.–></div>
<form action="https://www.webfulcreations.com/" id="my_form" method="post">
<table width="100%">
<tr>
<td>Your Name: </td>
<td><input type="text" name="name" value="Your name here.." /></td>
</tr>
<tr>
<td>Your Email: </td>
<td><input type="text" name="email" value="Your Email here… " /></td>
</tr>
<tr>
<td>Your Message: </td>
<td><textarea name="message">Your Message here.</textarea></td>
</tr>
</table>
</form>
<a href="#" onclick="submit_form()">Submit form</a>
</body>
</html>
[/code]
If you want to clear text field’s default text on click you can do like this
[code lang=”html”]
<input type="text" value="I am default value" onclick="this.value=”">
[/code]
There are several ways we can use to submit form using javaScript like on blur onchange onfocus onload and many others. This is up to us how we want to use that. The benefit of submitting form with javaScript is we can validate form easily as well in our submit function.