This article will show you how to submit form and change form action using javascript. This is a very simple trick but it’s very useful and frequently used.
Submit Form using Javascript
HTML form
<form name="myForm" action="http://google.com" method="get">
Search: <input type="text" name="q" />
<button onclick="javascript: submitForm()">Search</button>
</form>
Javascript function
function submitForm()
{
document.myForm.submit();
}
Change form action using Javascript
HTML form
<form name="newForm" method="get" onSubmit="formAction(this)">
Search: <input type="text" name="q" />
<input type="submit" name="search" value="Search">
</form>
Javascript function
function formAction()
{
document.newForm.action = "http://google.com";
}
Full Source Code
<html>
<head>
<title>Javascript and Forms</title>
<script type="text/javascript">
function submitForm()
{
document.myForm.submit();
}
function formAction()
{
document.newForm.action = "http://google.com";
}
</script>
</head>
<body>
<p>
Example 1: Submitting form through Javascript
<form name="myForm" action="http://google.com" method="get">
Search: <input type="text" name="q" />
<button onclick="javascript: submitForm()">Search</button>
</form>
</p>
<p>
Example 2: Changing form action through Javascript
<form name="newForm" method="get" onSubmit="formAction(this)">
Search: <input type="text" name="q" />
<input type="submit" name="search" value="Search">
</form>
</p>
</body>
</html>
Hope it helps. Thanks.