///Change Form Field Values, On The Fly, with JavaScript

Change Form Field Values, On The Fly, with JavaScript

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.

A live Master Survey form utilizing the technique presented in this article, with a different results page presentation depending on a demographic of the survey form user, is at http://willmaster.com/a/new/pl.pl?demosurvey

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.

http://willmaster.com/a/new/pl.pl?demosurvey is a live example using the technique presented in this article.

Adapt the technique as required to serve your needs.

2010-05-26T11:16:07+00:00 May 22nd, 2005|JavaScript|0 Comments

About the Author:

Leave A Comment