Mano Uncharted Mano Uncharted - 3 months ago 16
ASP.NET (C#) Question

How to enable and disable drop down list by selecting radio button in ASP.NET

I want to create a page in which whenever i select a particular radio item, a drop down list should be enabled and if some other item it selected the drop down list should be disabled.

This is my form script in ASP.NET

<form id="ticketbooking" class="book-ticket" runat="server">
<asp:Label ID="mode" runat="server" class="label">Mode of Travel</asp:Label><br />
<asp:RadioButton name="selector" ID="train" GroupName="travelmode" runat="server" value="tr"></asp:RadioButton>
<asp:Label ID="forTrain" for="train" runat="server" class="label">Train</asp:Label>
<div class="check"></div>
<asp:RadioButton name="selector" ID="air" GroupName="travelmode" runat="server" value="ar" OnCheckedChanged="air_CheckedChanged"></asp:RadioButton>
<asp:Label ID="forAir" for="air" runat="server" class="label">Air</asp:Label>
<div class="check"></div><br />
<asp:Label ID="airname" runat="server" class="label">Airline Name</asp:Label><br />
<asp:DropDownList class="droplist" ID="airlist" runat="server" Enabled="false" Font-Size="20px">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</form>


I have tried a few scripts as below but they wont work...

Method 1:

<script>
$(document).ready(function () {
$('input[name="selector"]').click(function () {
if ($('input[name="selector"]').is(':checked')) {
var radioValue = $("input[name='selector']:checked").val();
if (radioValue == "tr") {
$("#airlist").prop("disabled", true);
} else if (radioValue == "ar") {
$("#airlist").prop("disabled", false);
}
}
});
});
</script>


Method 2:

protected void air_CheckedChanged(object sender, EventArgs e)
{
if (air.Checked == true)
{
airlist.Enabled = true;
}
else
{
airlist.Enabled = false;
}
}


I tried both but its not working..when i click on the "Air" radio button the drop down list should be enabled..am i doing something wrong? need some suggestions please..i am still new to ASP.NET and not sure about how to work in this framework.

Answer

For Meyhod 1 put ClientIDMode="static" you JavaScript code will working fine LIKE

<asp:RadioButton ClientIDMode="static" name="selector" ID="train" GroupName="travelmode" runat="server" value="tr"></asp:RadioButton>

For Method 2 Put AutoPostback=true your C# will working fine LIKE

<asp:RadioButton AutoPostback="true" name="selector" ID="train" GroupName="travelmode" runat="server" value="tr"></asp:RadioButton>