PDA

View Full Version : Get the value of Radio Input from a form



Fighterfox
12-21-2010, 02:07 PM
I would like to know how to get the value of a selected radio button in a form. Suppose I want to use the following code:


<html>
<head>
<script type="text/javascript">
function score_form()
{
var opt = document.question.opt.value;
var element = document.getElementById('code');
element.innerHTML = "<form><fieldset>You have selected <b>" + opt + "</b>.</fieldset></form>";
}
</script>
</head>

<body>
<div id="code">
<form onsubmit="score_form()" name="question">
<fieldset>
<input type="radio" name="opt" value="option1" />Option 1<br />
<input type="radio" name="opt" value="option2" />Option 2<br />
<input type="submit" value="Score" />
</fieldset>
</form>
</div>
</body>
</html>

I get a value of undefined. Why? How can I get this code to work properly? Thanks in advance.

jscheuer1
12-21-2010, 02:46 PM
<html>
<head>
<script type="text/javascript">
function score_form(form){
var opts = form.elements['opt[]'], opt, element = document.getElementById('code');
for (var i = opts.length - 1; i > -1; --i){
if(opts[i].checked){
opt = opts[i].value;
break;
}
}
if(opt){
element.innerHTML = "<form><fieldset>You have selected <b>" + opt + "</b>.</fieldset></form>";
}
return false;
}
</script>
</head>

<body>
<div id="code">
<form onsubmit="return score_form(this);" name="question">
<fieldset>
<input type="radio" name="opt[]" value="option1" />Option 1<br />
<input type="radio" name="opt[]" value="option2" />Option 2<br />
<input type="submit" value="Score" />
</fieldset>
</form>
</div>
</body>
</html>