This is by far the funnest pieces of code I’ve written in a long time. So simple, so stupid, so useful! The scenario is you want users to click a radio button from a series of options…but only after they choose a parent radio button. In this example we want the user to select only one city from one state.
Add the radio buttons
I’m going to keep this simple, so we’ll have only two parent radio buttons:
<input type="radio" name="rdoState" value="Texas" onclick="EnableTexas()" /> <div id="DivTexas"> <input type="radio" name="rdoTexas" value="Austin" />Austin<br/> <input type="radio" name="rdoTexas" value="Dallas" />Dallas<br/> <input type="radio" name="rdoTexas" value="Houston" />Houston<br/> </div> <br/><br/> <input type="radio" name="rdoState" value="Virginia" onclick="EnableVirginia()" /> <div id="DivVirginia"> <input type="radio" name="rdoVirginia" value="Arlington" />Arlington<br/> <input type="radio" name="rdoVirginia" value="McLean" />McLean<br/> <input type="radio" name="rdoVirginia" value="Reston" />Reston<br/> </div>
Add jQuery function for onclick event
We are going to add two functions, and one initialization routine to disable all the child radio buttons by default. First, we initialize everything to be unchecked and disabled, pretty self-explanatory:
$(function() {
//init Texas
$('#DivTexas :input').attr('checked', false);
$('#DivTexas :input').attr('disabled', true);
//init Virginia
$('#DivVirginia :input').attr('checked', false);
$('#DivVirginia :input').attr('disabled', true);
});
Next we add the two onclick functions:
function EnableTexas()
{
//disable Virginia options
$('#DivVirginia :input').attr('checked', false);
$('#DivVirginia :input').attr('disabled', true);
//enable Texas options
$('#DivTexas :input').removeAttr('disabled');
}
function EnableVirginia()
{
//disable Texas options
$('#DivTexas :input').attr('checked', false);
$('#DivTexas :input').attr('disabled', true);
//enable Virginia options
$('#DivVirginia :input').removeAttr('disabled');
}




