| Answer: |
This really isn't an ASP question (since you are using client-side JavaScript), but it's a commonly asked question so I figured it warranted an answer here. Say that we have a form with two buttons, and, depending on the button clicked, we'd like to programmatically set the form's action and submit it. Given the following HTML code for the form:
<FORM NAME="MyFirstForm"> <INPUT TYPE=TEXT NAME=MyName><BR> <INPUT TYPE=BUTTON VALUE="Add" ONCLICK="Add();"> <INPUT TYPE=BUTTON VALUE="Delete" ONCLICK="Delete();"> </FORM>
|
All we need to do to alter the form's action is write the Add() and Delete() client-side JavaScript functions:
<SCRIPT LANGUAGE="JavaScript"> <!-- function Add() { // alter the action and submit the form document.MyFirstForm.action = "AddName.asp"; document.MyFirstForm.submit(); }
function Delete() { // alter the action and submit the form document.MyFirstForm.action = "DeleteName.asp"; document.MyFirstForm.submit(); } // --> </SCRIPT>
|
Note that each JavaScript function is comprised of only two lines of code. The first dynamically alters the form's ACTION property and the second actually submits the form. Pretty neat, eh?
Another common request is how to change the form's action based upon a select box's value. To rig this up, all we need to do is wire the select box's ONCHANGE event to a JavaScript function that sets the action property of the form based upon the select box's current value. Given the following HTML code:
<FORM NAME=MyFirstForm ACTION="AddName.asp"> <INPUT TYPE=TEXT NAME=MyName><BR> <SELECT NAME=MySelectBox ONCHANGE="AlterAction();"> <OPTION SELECTED VALUE="AddName.asp">Add</OPTION> <OPTION VALUE="DeleteName.asp">Delete</OPTION> </SELECT> <P> <INPUT TYPE=SUBMIT> </FORM>
|
Note that this is strikingly similar to the first code sample. The difference is that instead of using two buttons to determine the action, we are letting the user make a selection via a select box. The only thing left to do is write the client-side JavaScript AlterAction() function. (Note that the form's action is currently set to AddName.asp, which is the default select box option... this is in case the ONCHANGE event doesn't fire (i.e., the user doesn't change the select box values before submitting the form).)
<SCRIPT LANGUAGE="JavaScript"> <!-- function AlterAction() { document.MyFirstForm.action = document.MyFirstForm.MySelectBox.value; } // --> </SCRIPT>
|
There you go! For more information on HTML tags, form elements, and client-side JavaScript coding, be sure to check out http://developer.netscape.com/! |