How to show/hide divs based on radio button selection using jQuery

Tags: |

If you want a radio button selection to show certain Div contents and hide some other Div on the web page, and on another radio button selection, you need a different Div associated with that radio button hiding the unwanted one, read on.

This can be achieved very efficiently using jQuery. We can put the code inside “click” or “change” event of radio button group,

$("input[name$='group_name']").click(function(){
  }

and after getting the value of selected radio button by this:

var radio_value = $(this).val();

We can simply hide or show our required Divs using following:

 if(radio_value=='Yes') {
  $("#yes_box").show("slow");
  $("#no_box").hide();
  }

Here’s putting every together, simply put this code in your page inside script tags and it will work.

$(document).ready(function(){
 
  $("input[name$='group_name']").click(function(){
 
  var radio_value = $(this).val();
 
  if(radio_value=='Yes') {
    $("#yes_box").show("slow");
     $("#no_box").hide();
  }
  else if(radio_value=='No') {
   $("#no_box").show("slow");
    $("#yes_box").hide();
   }
  });
 
  $("#yes_box").hide();
  $("#no_box").hide();
 
});

Here is the demonstration of this.

You can see it here in new window as well.

Hope that helps.

Cheers.

Related posts:

  1. How to show/hide content based on select onchange using jQuery
  2. How to align checkboxes/radio buttons and their labels
  3. [osCommerce] Change Currency Selection based on Payment Module on checkout_confirmation page in osCommerce Store
  4. [AS3] Dynamically create button MovieClips and center align container MovieClip on stage in Flash
  5. WordPress Gravity Forms Validation on Client Side using jQuery