Home|Sitemap|Contact

How can you check radio buttons values or to see if at least one has been checked?

If you are here, you have discovered radio.value does not return the value selected and if (radio.checked) does not tell you if a radio button has been checked.  Why Not?

Radio buttons are groups.  e.g. radio[0], radio[1]...

Each member of the group has a value and a checked property.  To get the value of the radio group or to see if one of the group has been checked, you have to loop through the radio group.

Radios: 1: 2: 3: 4: 5:  


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

<head>
<title>check radio groups</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005, 2006 Roderick Divilbiss">
<script type="text/javascript">
<!--
function isRadioChecked(fld) {
    for (var idx=0;idx<fld.length;idx++)
        if (fld[idx].checked)
        return true;
    return false;
}

function getRadioValue(fld) {
    for (var idx=0;idx<fld.length;idx++)
        if (fld[idx].checked)
        return fld[idx].value;
    return '';
}
//-->
</script>
</head>

<body>
<form name="frm">
Radios: 1:<input type="radio" value="1" id="r1" name="r1"> 2:<input type="radio" value="2" id="r1" name="r1"> 3:<input type="radio" value="3" id="r1" name="r1"> 4:<input type="radio" value="4" id="r1" name="r1"> 5:<input type="radio" value="5" id="r1" name="r1">&nbsp;&nbsp; <input type="button" value="isRadioChecked" name="B1" onclick="alert(isRadioChecked(document.frm.r1));"> <input type="button" value="getRadioValue" name="B2" onclick="alert(getRadioValue(document.frm.r1));">
</form>
</body>

</html>