[jquery] How to use jQuery to show/hide divs based on radio button selection?

I have some radio buttons and I'd like to have different hidden divs show up based on which radio button is selected. Here's what the HTML looks like:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" value="opt2">opt2</label></div>  
    <div><label><input type="radio" name="group1" value="opt3">opt3</label></div>  
    <input type="submit" value="Submit">
</form>

....

<style type="text/css">
    .desc { display: none; }
</style>

....

<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc">consectetur adipisicing</div>
<div id="opt3" class="desc">sed do eiusmod tempor</div>

And here's my jQuery:

$(document).ready(function(){ 
    $("input[name$='group2']").click(function() {
        var test = $(this).val();
        $("#"+test).show();
    }); 
});

The reason I'm doing it that way is because my radio buttons and divs are being generated dynamically (the value of the radio button will always have a corresponding div). The code above works partially - the divs will show when the correct button is checked, but I need to add in some code to make the divs hide again once the button is unchecked. Thanks!

This question is related to jquery radio-button mouseclick-event

The answer is


<script type="text/javascript">
$(function() {
    $("[name=toggler]").click(function(){
            $('.toHide').hide();
            $("#blk-"+$(this).val()).show('slow');
    });
 });
</script>
</head>
<body>
<label><input id="rdb1" type="radio" name="toggler" value="1" />Book</label>
<label><input id="rdb2" type="radio" name="toggler" value="2" />Non-Book</label>

<div id="blk-1" class="toHide" style="display:none">

    <form action="success1.html">

        Name1:<input type="text" name="name">
             <input type="submit" name="submit">

    </form>

</div>
<div id="blk-2" class="toHide" style="display:none">

    <form action="success1.html">

        Name2:<input type="text" name="name">
             <input type="submit" name="submit">

    </form>
</div>

The simple jquery source for the same -

$("input:radio[name='group1']").click(function() {      
    $('.desc').hide();
    $('#' + $("input:radio[name='group1']:checked").val()).show();
});

In order to make it little more appropriate just add checked to first option --

<div><label><input type="radio" name="group1" value="opt1" checked>opt1</label></div>  

remove .desc class from styling and modify divs like --

<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc" style="display: none;">consectetur adipisicing</div>
<div id="opt3" class="desc" style="display: none;">sed do eiusmod tempor</div>

it will really look good any-ways.


You can use jQuery’s show() and hide() methods. Like below:

JQuery:

  $(document).ready(function(){
    $('input[type="radio"]').click(function(){
      var val = $(this).attr("value");
      var target = $("." + val);
      $(".msg").not(target).hide();
      $(target).show();
    });
  });

HTML:

<input type="radio" name="color" value="yellow"> Yellow
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green

<div class="yellow msg">You have selected Yellow</div>
<div class="red msg">You have selected Red</div>
<div class="green msg">You have selected Green</div>

Here is an example: Show/hide DIV based on Radio Button click


An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked with the id of the checkbox or radio button on which it depends. That is, your form looks like this:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" id="rdio1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" id="rdio2" value="opt2">opt2</label></div>  
</form>
....
<div id="opt1" automaticallyVisibleIfIdChecked="rdio1">lorem ipsum dolor</div>
<div id="opt2" automaticallyVisibleIfIdChecked="rdio2">consectetur adipisicing</div>

and have some page independent JavaScript that nicely uses functional programming:

function executeAutomaticVisibility(name) {
    $("[name="+name+"]:checked").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
    });
    $("[name="+name+"]:not(:checked)").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
    });
}

$(document).ready( function() {
    triggers = $("[automaticallyVisibleIfIdChecked]")
        .map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
    $.unique(triggers);
    triggers.each( function() {
        executeAutomaticVisibility(this.name);
        $(this).change( function(){ executeAutomaticVisibility(this.name); } );
    });
});

Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked.

I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.


$(document).ready(function(){ 
    $("input[name=group1]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

It's correct input[name=group1] in this example. However, thanks for the code!


Below code is perfectly workd for me:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('input[type="radio"]').click(function(){_x000D_
        var inputValue = $(this).attr("value");_x000D_
        var targetBox = $("." + inputValue);_x000D_
        $(".box").not(targetBox).hide();_x000D_
        $(targetBox).show();_x000D_
    });_x000D_
});
_x000D_
.box{_x000D_
        color: #fff;_x000D_
        padding: 20px;_x000D_
        display: none;_x000D_
        margin-top: 20px;_x000D_
    }_x000D_
    .red{ background: #ff0000; }_x000D_
    .green{ background: #228B22; }_x000D_
    .blue{ background: #0000ff; }_x000D_
    label{ margin-right: 15px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
        <label><input type="radio" name="colorRadio" value="red"> red</label>_x000D_
        <label><input type="radio" name="colorRadio" value="green"> green</label>_x000D_
        <label><input type="radio" name="colorRadio" value="blue"> blue</label>_x000D_
    </div>_x000D_
    <div class="red box">You have selected <strong>red radio button</strong> so i am here</div>_x000D_
    <div class="green box">You have selected <strong>green radio button</strong> so i am here</div>_x000D_
    <div class="blue box">You have selected <strong>blue radio button</strong> so i am here</div>
_x000D_
_x000D_
_x000D_


I wrote a simple code to unterstand you to how to make a show and hide radio buttons in jquery its very simple

<div id="myRadioGroup">

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

    Percent Based<input type="radio" name="cars" value="3" />
    <br>
    <div id="Cars2" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Value</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Percent</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
</div>
</div>

Jquery code

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

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

give me comments


Just hide them before showing them:

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