show and hide divs based on radio button click

Kiksy picture Kiksy · May 9, 2011 · Viewed 193.5k times · Source

I want to be able to dynamically change what divs are show using radio button and jQuery - HTML:

  <div id="myRadioGroup">

2 Cars<input type="radio" name="cars" checked="checked" value="2"  />

3 Cars<input type="radio" name="cars" value="3" />

<div id="twoCarDiv">
2 Cars Selected
</div>
<div id="threeCarDiv">
3 Cars
</div>
</div>

and the jQuery:

     <script>
$(document).ready(function(){ 
    $("input[name$='cars']").click(function() {
        var test = $(this).val();
        $("div.desc").hide();
        $("#"+test).show();
    }); 
});
</script>

This does nothing , the divs always show. Im sure this is simple, but Im poor at jQuery .

Answer

Jason McCreary picture Jason McCreary · May 9, 2011

You're on the right track, but you forgot two things:

  1. add the desc classes to your description divs
  2. You have numeric values for the input but text for the id.

I have fixed the above and also added a line to initially hide() the third description div.

Check it out in action - http://jsfiddle.net/VgAgu/3/

HTML

<div id="myRadioGroup">
    2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
    3 Cars<input type="radio" name="cars" value="3" />

    <div id="Cars2" class="desc">
        2 Cars Selected
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        3 Cars
    </div>
</div>

JQuery

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});