Change Form Field Values "On The Fly" with JavaScript
Some forms require a different confirmation page depending
on the selection of an answer to a question
This article will demonstrate how to automatically change
a form field's value depending on which radio button is
clicked.
This article's example form name will be "MyForm".
The field to be changed will be "redirect". And the radio
button fields that affect the value of the "redirect" field
will be named "age".
<form
name="MyForm"
method="POST"
action="/cgi-bin/script.cgi">
<input
type="hidden"
name="redirect"
value="/default.html">
<input
type="radio"
name="age"
value="/young.html">
I am young<br><br>
<input
type="radio"
name="age"
value="/middle.html">
I am middle-aged<br>
<input
type="radio"
name="age"
value="/old.html">
I am old<br>
<input
type="submit"
value="Submit this Form!"
onclick="return DetermineDestination();">
</form>
Notice that the submit button field has an attribute that
returns the value of a Java function. If the value
being returned is "true," the form will submit. If the
value is "false," the form will not submit.
The JavaScript function changes the value of the "redirect"
field depending on which "age" radio button was checked. If
an "age" radio button was checked, the JavaScript function
returns "true." If no radio button was checked, an alert
box pops up with a message and the function returns "false."
Here is the JavaScript:
<script type="text/javascript" language="JavaScript"><!--
function DetermineDestination() {
var chosen = false;
for(var i = 0; i < document.MyForm.age.length; i++) {
if(document.MyForm.age[i].checked == true) {
document.MyForm.redirect.value =
document.MyForm.age[i].value;
chosen = true;
break;
}
}
if(chosen == false) {
setTimeout("alert('An age must be checked.')",1500);
}
return chosen;
}
//--></script>
The above JavaScript may be put into the HEAD or BODY area
of the web page, above or below the form. It will work as
presented here.
Adapt the technique as required to serve your needs.
Question:
Did you find this article interesting and understandable? How can it be improved?
Your response is anonymous.
When done typing, click anywhere outside the box. [more info]
Will Bontrager
©2005 Bontrager Connection, LLC
Please note:
Articles on this website are presented "as is". However -
If you have a question about a CGI script, HTML, CSS, PHP, or JavaScript
Ask one of our Experts and you'll have your answer!
Click here for details.