Reputation: 185
I am a bit baffled on this. I have this html -
<input type="radio" id="20577091" name="q_engine" value="20577091" style="position: absolute; opacity:0;" checked="checked" />
and this javascript
var chosen = '';
len = document.quote_form.q_engine.length;
for (i = 0; i < len; i++) {
if (document.quote_form.q_engine[i].checked) {
chosen = document.quote_form.q_engine[i].value
}
}
For some reason it will not validate. I have the radio element selected but when submit (and alert var chosen it is empty.
I have another form with multiple radio buttons w/ labels. If a label is clicked, the radio is selected and validation works.
Any help would be appreciated.
Thanks.
Upvotes: 0
Views: 85
Reputation: 56
As single radio button doesn't have length property so you need add the condition to make it work,
<html><body>
<form name="quote_form">
<!--Radio 1 : <input type="radio" id="20577090" name="q_engine" value="20577090" />-->
Radio 2 : <input type="radio" id="20577091" name="q_engine" value="20577091" checked="checked" />
</form>
<script type="text/javascript">
var chosen = '';
if (document.quote_form.q_engine.checked) {
chosen = document.quote_form.q_engine.value
}
else {
len = document.quote_form.q_engine.length;
for (i = 0; i < len; i++) {
if (document.quote_form.q_engine[i].checked) {
chosen = document.quote_form.q_engine[i].value
}
}
}
alert(chosen);
</script>
</body>
</html>
The above code will work whether you have one radio button or more than one radio buttons!
You can read more on this here - http://www.falsepositives.com/index.php/2007/10/16/javascript-for-a-single-element-radio-button-list/
Upvotes: 1
Reputation: 8741
This worked in Google Chrome with the same code:
<html>
<head>
</head>
<body>
<form name="quote_form">
<input type="radio" id="20577090" name="q_engine" value="20577090" style="position: absolute; opacity:0;" />
<input type="radio" id="20577091" name="q_engine" value="20577091" style="position: absolute; opacity:0;" checked="checked" />
</form>
<script>
var chosen = '';
len = document.quote_form.q_engine.length;
var chosen = '';
len = document.quote_form.q_engine.length;
for (i = 0; i < len; i++) {
if (document.quote_form.q_engine[i].checked) {
chosen = document.quote_form.q_engine[i].value
}
}
alert(chosen);
</script>
</body>
</html>
Script is placed after form.
Upvotes: 0