Dynamically change a form's action with JavaScript

Posted Dec 11, 2008
Last Updated Nov 12, 2011

You can dynamically change the action of a form embedded in a web page by referencing the form in JavaScript. Suppose your HTML contained:

<form id= "myForm" action= "doMySubmission.php" >
<input type= "submit" value= "Submit"/>
</form>

You could write a JavaScript to change where the form submits to with code such as that below:

<script type="text/javascript">

/ / For Google Chrome
document.getElementById('myForm').action.value='/action1.php';

/ / For IE and Firefox
document.getElementById('myForm').action='/action1.php';

</script>

While a more realistic scenario is to write a function that changed the form action based on the input the user gave, the example shows the principle.

Before Google Chrome, I referenced the action with just a straight myForm.action = 'newAction' but Chrome seems to be flaky in honoring that syntax. Adding the extra property level of .value makes the syntax work well in Chrome; it does not work in the other browsers I have tested so far... so you have to write the code for Chrome and other browsers separately.

Comment

No HTML Tags are permitted.

Angry Teapot Level Design Awards

Newsletter Subscription