[ Team LiB ] Previous Section Next Section

8.5 Changing a Form's Action

NN 2, IE 3

8.5.1 Problem

You want to submit a form to a different action depending on user activity in the page.

8.5.2 Solution

The most common scenario is a form with two or more buttons that submit the form, but each button directs the form to a different CGI program on the server. If you use submit-type input elements, use the onclick event handlers to assign the desired CGI URL to the action property of the form:

<input type="submit" value="Send To HeadQuarters" 
onclick="this.form.action='../main.megacorp.com/submitSpecs.asp'" />
<input type="submit" value="Send For Peer Review" 
onclick="this.form.action='../eng.megacorp.com/reviewComm.asp'" />

Any function executing before the form submits itself can assign a URL to the form element's action property to influence where the form goes.

8.5.3 Discussion

Deploying this solution to a browser base that may include nonscriptable browsers (including browsers with scripting turned off) should be done with care. Your first inclination might be to assign a default action URL in the form that receives the form if scripting is not available. But if you use two submit-type input elements, as shown in the example, both buttons will submit the form to the default action, regardless of the label in the button. This could mislead your scriptless visitors.

You aren't limited to using submit-type input elements, of course. For example, your form may contain a checkbox that acts as a signal for which action the form should follow. In this case, the onsubmit event handler of the form can inspect the checked property of the checkbox button, and set the action property's URL before allowing the submission to continue:

form.action = (form.myCheckbox.checked) ? "cgi-bin/special.pl" : "normal.jsp";

Bear in mind that the action attribute is required in a form element under all recent HTML and XHTML validation scenarios.

8.5.4 See Also

Recipe 8.3 for using the onsubmit event handler to perform last-instant processing before form submission.

    [ Team LiB ] Previous Section Next Section