Dynamically change a form's action with JavaScript

Dynamically change a form's action with JavaScript

By Shawn Olson

Posted on December 12th, 2008

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='/anotherDirectory/alternativeAction.php';

/ / For IE and Firefox
document.getElementById('myForm').action='/anotherDirectory/alternativeAction.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.

Copyright © 2008-2009 by Shawn Olson.
sitemap RGB Color Columbus Photography Free Word Search Maker monty hall game Hangman John Dewey