Sunday, June 2, 2013

Display and Hide a RadioButton Based on a condition using jQuery


<html xmlns="">
<head runat="server">
<title>Hide a RadioButton based on a condition</title>
<script src=""></script>
<script type="text/javascript">
$(function() {
var $tbl = $('table.tbl');
var $selRadio = $("table.tbl input:radio[value='0']");
$('.cls input:radio').click(function(e) {
var whichRad =;
if (whichRad === $("input:radio[id$=rDel]").attr("id")) {
else if (whichRad === $("input:radio[id$=rTake]").attr("id")) {

<form id="form1" runat="server">
<div class="smallDiv">
<h2>Selectively Hide/Show Controls</h2><br />
Do you want a Delivery or Take Away?<br />

<asp:RadioButton ID="rDel" runat="server" Text="Delivery" GroupName="Mode" class="cls" />

<asp:RadioButton ID="rTake" runat="server" Text="Take Away" GroupName="Mode" class="cls" />

<br /><hr />

Payment Options<br />

<asp:RadioButtonList ID="rbl" runat="server" class="tbl">
<asp:ListItem Text="Credit Card" Value="0"></asp:ListItem>
<asp:ListItem Text="Coupons" Value="1"></asp:ListItem>
<asp:ListItem Text="Cash" Value="2"></asp:ListItem>



In this example, we ask the user to choose between two options – ‘Delivery’ or ‘TakeAway’. The CreditCard payment option is shown only if the user opts for ‘TakeAway’.

Since this is a RadioButtonList, the control gets rendered as a table. Since this list has class ‘tbl’ applied to it, hence we reference the control as $('table.tbl').

We first cache the table object and the first radio button in separate variables as shown below:

var $tbl = $('table.tbl');
var $selRadio = $("table.tbl input:radio[value='0']");

We start by hiding the payment options $tbl.hide(); and then detect the radio button clicked (Delivery or TakeAway) by using var whichRad =;

If the user chooses the ‘Delivery’ option, the ‘CreditCard’ payment radio button is hidden as shown in the screenshot below:

This is done using the following code:

if (whichRad === $("input:radio[id$=rDel]").attr("id")) {

You must be wondering why are we calling hide() twice. This is because the RadioButton gets rendered as the following markup:

<t d>
<input id="rbl_0" type="radio" name="rbl" value="0" />
<label for="rbl_0">Credit Card</label>

So to hide the RadioButton as well as its label, we use .hide().next().hide(); The first hide() hides the RadioButton. We use next() which finds the very next sibling of each radio button, which in our case is the label control and then call hide() again, to hide the label. This is a nice demonstration of method chaining. Similarly, when the user chooses ‘TakeAway’, the ‘CreditCard’ payment radio button is made visible using


The output is shown below:

No comments:
Write comments
Recommended Posts × +