Show box if radio button checked using jQuery

Cameron picture Cameron · Sep 24, 2010 · Viewed 17.5k times · Source

I have the following code:

    <fieldset>
        <legend>Do you currently have SolidWorks</legend>

        <ul>
            <li><label for=""><input type="radio" name="solidworks" value="Yes" id="rdYes" /> Yes</label></li>
            <li><label for=""><input type="radio" name="solidworks" value="No" id="rdNo" /> No</label></li>
        </ul>
    </fieldset>

    <fieldset id="boxReseller" style="display:none;">
        <legend>Who is your SolidWorks reseller?</legend>
        <ul>
            <li><label for=""><input type="radio" name="reseller" value="Cad Connect" /> Cad Connect</label></li>
            <li><label for=""><input type="radio" name="reseller" value="Cadtek" /> Cadtek</label></li>
            <li><label for=""><input type="radio" name="reseller" value="CCSL" /> CCSL</label></li>
            <li><label for=""><input type="radio" name="reseller" value="Innova" /> Innova</label></li>
            <li><label for=""><input type="radio" name="reseller" value="NT CAD/CAM" /> NT CAD/CAM</label></li>
            <li><label for=""><input type="radio" name="reseller" value="Solid Engineer" /> Solid Engineer</label></li>
            <li><label for=""><input type="radio" name="reseller" value="Solid Solutions Ireland" /> Solid Solutions Ireland</label></li>
            <li><label for=""><input type="radio" name="reseller" value="Solid Solutions Management" /> Solid Solutions Management</label></li>
            <li><label for=""><input type="radio" name="reseller" value="TMS Scotland" /> TMS Scotland</label></li>
        </ul>

    </fieldset>

What I want to do is hide the second fieldset by default and if a person chooses Yes then the box will appear, and if they choose No or Yes is not selected then the box will hide again.

Can anyone help? Thanks.

Answer

Nick Craver picture Nick Craver · Sep 24, 2010

You could do this:

$("input[name='solidworks']").change(function() {
  $("#boxReseller").toggle(this.value == "Yes");
});​​​​​​
$("input[name='solidworks']:checked").change(); //trigger correct state onload

You can give it a try with the markup in the question here, and try the pre-checked "Yes" version here.