Click to See Complete Forum and Search --> : processing data from a radio button in a form


spacesaver
11-21-2003, 11:15 AM
I'm trying to write a simple function that will add the value field of a radio button to a string. I was succesful doing this with a text box, but not the radio button. When i run the program, entering a name, age and selecting a gender with a radio value, I keep getting "undefined value" where the gender should be!
Any ideas? Please post them!!!

this is the code:

<html>
<body>
<head><script language = "javascript">

function makeStory(){
var newStory1 = ("This is a story about " + document.madlib.name.value + ". " + document.madlib.name.value + " is " + document.madlib.age.value + " years old. ")
var newStory2 = (document.madlib.name.value + " is of the " + document.madlib.gender.value + " gender")
document.madlib.story.value = newStory1 + newStory2
}

</script>
</head>


<form name = "madlib">

<table align = "center">
<tr>
<th colspan = 2>Please enter text into the following fields: </th>

<tr>
<td>Enter your name:</td>
<td><input name = "name" type = "text" size = "40"></td></tr>
<tr>
<td>Enter your age:</td>
<td><input name = "age" type = "text" size = "40"></td></tr>
<tr>
<td>Select your gender:</td>
<td><input name = "gender" type = "radio" value = "female"> female<br>
<input name = "gender" type = "radio" value = "male"> male </td></tr>

<tr>
<td><input name = "makestory" type = "button" value = "create the story" onClick = "makeStory()"></td>
<td></td>

<tr> <td> Your Story </td>
<td><textarea name = "story" type = "text" rows = 7 cols = 40></textarea></td>
</tr>

</table>
</body>
</html>

gil davis
11-21-2003, 11:37 AM
When you have more than one element with the same name, you get an array. The array doesn't have a value parameter, the elements of the array do. So document.madlib.gender[0].value will have what you want. The problem is, you need to use the one that is checked.
var tmp = document.madlib.gender[0].checked ? document.madlib.gender[0].value : document.madlib.gender[1].value;

spacesaver
11-21-2003, 12:51 PM
thanks for the help Gil!!