Check/Uncheck/Disable Radio Buttons with JavaScript

There may be occasions when you will need to check, uncheck, or disable radio buttons based on other form entries. The following form demonstrates one such scenario. Try checking and unchecking the "Hazardous Items" checkbox in the form to see how this affects your choice of shipping method:

Demo: Check/Disable using JavaScript

Shipping method:

If the Hazardous Items checkbox is checked, standard shipping is selected and the other two options are disabled.

JavaScript for the Example

The JavaScript for the form above is displayed and described here:

// assign onclick handler to hazard checkbox
document.getElementById('hazard').onclick = function() {

    // is hazard checkbox checked?
    var hazard = this.checked; // true or false

    // get list of radio buttons with name 'ship'
    var radios = this.form.elements['ship'];

    // loop through list of radio buttons
    for (var i=0, len=radios.length; i<len; i++) {
        var r = radios[i]; // current radio button

        if ( hazard ) { // hazard checkbox checked

            if ( r.value === 'std' ) { // standard shipping
                r.checked = true; // set checked
            } else { // not standard shipping
                r.checked = false; // unchecked
                r.disabled = true; // disable
            }

        } else { // hazard not checked
            r.disabled = false; // no radios disabled
        }

    }
}

A function is assigned to handle the click event of the hazard checkbox. It determines whether the checkbox is checked and inspects each radio button in turn. With the hazard checkbox checked, if the current radio button is standard shipping, it is checked. The other radio buttons have their checked property set false and disabled property set true. If the hazard checkbox is not checked, none of the radio buttons are disabled: their disabled properties are set false.

Markup for Example Form

Markup for the example form is displayed below:

<form action="#" method="post" class="demoForm" id="demoForm">
    <fieldset>
        <legend>Demo: Check/Disable using JavaScript</legend>
        
    <p><label>Hazardous Items? <input type="checkbox" id="hazard" name="hazard" value="hazard" /></label></p>
    
    <p>Shipping method:</p>
    
    <p>
        <label><input type="radio" name="ship" value="std" /> Standard Ground</label>
        <label><input type="radio" name="ship" value="2day" checked /> Second Day</label>
        <label><input type="radio" name="ship" value="1day" /> Overnight</label>
    </p>
        
    </fieldset>

</form>