PDA

View Full Version : Problem with Passing Form Value


narino
05-11-2010, 05:54 AM
Dear all

I know this must be so easy for you guys, but I was unable to find the answer. Please help.

I wrote this form to try to display the value of the chosen radio button on a text input.

<form>
Choose one choice...
<input type="radio" name="group1" value="5">Five<br>
<input type="radio" name="group1" value="10">Ten<br>

<input type="button" value="Get Result!" onClick="T1.value=group1.value"><br>

Your choice is
<input type="text" size="2" value="0" name="T1">
</form>



How come the onClick="T1.value=group1.value" results in undefined instead of 5 (or 10) ?

How do I fix it?

Thanks a lot,
Narin

Kor
05-11-2010, 12:45 PM
group1 is the common name of all the radios in a group, not of a single element, thus it will refer a collection of elements, not a single element. You must circle through that collection and see what element is checked.

And use a function:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function setValue(txtName,radiosName){
var radios=document.getElementsByName(radiosName), r, i=0;
while(r=radios[i++]){
if(r.checked){
document.getElementsByName(txtName)[0].value=r.value;
break
}
}
}
</script>
</head>
<body>
<form action="">
Choose one choice...
<input type="radio" name="group1" value="5">Five<br>
<input type="radio" name="group1" value="10">Ten<br>

<input type="button" value="Get Result!" onclick="setValue('T1','group1')"><br>

Your choice is
<input type="text" size="2" value="0" name="T1">


</form>
</body>
</html>

narino
05-11-2010, 09:39 PM
Thanks so much!