How to Submit a Form Using JavaScript?



Sometimes, you may need to submit a form programmatically using Javascript in contrast to the standard user way of submitting the form by clicking on the form.

Javascript provides the submit() method to allow for form submit from javascript.

Javascript Submit() method Example 1

document.forms["formname"].submit();

In the code above, formname is the name of the form we want to do the submit on using javascript.

Javascript Submit() method Example 2

<form name="formvar" action="submit.php">
<input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
  document.formvar.submit();
}
</script> 

In the code above, formvar is the name of the form we want to do the submit on using javascript. Note, we are calling this function on submitform event associated with the link.

Therefore, the complete code looks like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="container">
 <form name="formvar" action="submit.php">
<input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
  document.formvar.submit();
}
</script> 
</div>
</body>
</html>

If you are looking to find out how to submit a form using Jquery, click on the link.