Radio Button checked and defaultChecked Properties
The checked
property of a radio button tells you whether it is currently selected. The defaultChecked
property of a radio button tells you whether it includes the checked
attribute in the markup, as the first radio button shown below does:
<input type="radio" name="ship" value="std" checked /> Standard Ground
<input type="radio" name="ship" value="2day" /> Second Day
<input type="radio" name="ship" value="1day" /> Overnight
<input type="radio" name="ship" value="hold" /> Pick up
The following JavaScript inspects the defaultChecked
property of the first radio button in the group:
alert(document.forms.demoForm.elements.ship[0].defaultChecked); // true
The alert displays true
since the first radio button includes the checked
attribute in markup.
Compare User Selection with defaultChecked
You may occasionally want to determine whether the currently selected radio button in a group is selected by default. Try selecting various radio buttons in the form above, and then click the "Check if Default" button to see the result.
The following function will return true or false depending upon whether the currently selected radio button in the group is checked in the markup:
function checkDefault(form, name) {
// get list of radio buttons with specified name
var radios = form.elements[name];
// loop through list of radio buttons
for (var i=0, len=radios.length; i<len; i++) {
// inspect checked and defaultChecked properties
if ( radios[i].checked && radios[i].defaultChecked ) {
return true; // return true from function if both true
}
}
return false; // return false if checked radio not default
}
If a radio button is both checked
and defaultChecked
, the function returns true
. The following demonstrates how to invoke the function for this example:
// pass reference to form and name of radio group to checkDefault function
var dflt = checkDefault(document.forms['demoForm'], 'ship');
alert(dflt);