7.7. Determining the Action Based on User Input
Problem
You want to change the target action for a form based on user input.
Solution
Call a JavaScript function, like the one shown in Example 7-5, from an event handler on the HTML control that determines the action.
Example 7-5. JavaScript function to change a form's action
<script>
function swapAction(control) {
formAction = document.getElementById("empForm").action;
if (control.checked)
newAction = '<html:rewrite page="/CreateEmployee.do"/>';
else
newAction = '<html:rewrite page="/UpdateEmployee.do"/>';
document.getElementById("empForm").action = newAction;
}
</script>
<html:form styleId="empForm" action="/UpdateEmployee">
New Employee: <html:checkbox property="create"
onclick='swapAction(this)"'/><br />
... rest of the pageDiscussion
JavaScript makes this problem easy to solve. You might be tempted to
hardcode the new value for the action in the function. However, the
function will be a lot more robust if you use the
html:rewrite tag.
Using this tag ensures the action URI includes the appropriate
application context prefix. It generates the session token if cookies
are disabled. You can verify this works by disabling cookies on your
browser. If you clicked the "New
Employee" checkbox and submit the form
you'd see a URL like the following:
http://localhost/jsc-ch05/CreateEmployee.do;jsessionid= C0691FF1D538431815A448C4278BA999
If you had hardcoded the action, you'd lose the session. The drawback to this solution is you must specify the ...