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

by Ali on June 10th, 2010

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();
 
});

Hope that helps.

Cheers.

No related posts.

No comments yet

Leave a Reply

You must be logged in to post a comment.