JavaScript Phrasebook

var btn = f.elements["radiobutton"][i]; s += btn.value + ": " + btn.checked + "\n";

Unlike check boxes, HTML radio buttons always come in groups. That means that several radio buttons may have the same name attribute, but differ in their value attributes. Therefore, document.forms[number].elements[radiobuttongroup] accesses the whole group of radio buttonsthat is, it is an array. Every subelement of this array is a radio button and supports the checked property. This property works analogous to the check box's checked property: TRue means that the radio button is activated, and false stands for the opposite.

Access to the value of every button is possible, as well: the value property takes care of that.

The following code iterates through all radio buttons and outputs their state:

Accessing a Group of Radio Buttons (radiobutton.html)

<script language="JavaScript" type="text/javascript"> function showStatus(f) { var s = ""; for (var i=0; i<f.elements["radiobutton"].length; i++) { var btn = f.elements["radiobutton"][i]; s += btn.value + ": " + btn.checked + "\n"; } window.alert(s); } </script> <form> <input type="radio" name="radiobutton" value="R" />red <input type="radio" name="radiobutton" value="G" />green <input type="radio" name="radiobutton" value="B" />blue <input type="button" value="Show status" onclick="showStatus(this.form);" /> </form>

Категории