Introduction
Sometimes, we may come across a situation where we have few DropDownList
s and when we select a value from a particular DropDown
, all the other DropDown
s should reset to their default value. Here, I have given a solution for that situation.
Using the Code
Let us assume that you have this table structure which includes 3 DropDownList
s and a Text Box which displays the selection you made in the DropDownList
.
<table>
<tbody>
<tr style="width: 100%">
<th colspan="3">
This is to reset all other dropdownlist when a dropdowns selection changes
</th>
</tr>
<tr>
<td>
<asp:DropDownList ID="DropDownList1"
onchange="DisableOtherDropdowns(this)" runat="server">
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="DropDownList2"
onchange="DisableOtherDropdowns(this)" runat="server">
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="DropDownList3"
onchange="DisableOtherDropdowns(this)" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr style="width: 100%">
<td>
<asp:Label ID="lblSelectedField"
runat="server" Text="Selected Text"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSelectedText"
runat="server"></asp:TextBox>
</td>
</tr>
</tbody>
</table>
Now I have created a DataTable
with 2 columns and binded that to the DropDownList
s.
DataTable dt = new DataTable();
dt.Columns.Add("Student Id");
dt.Columns.Add("Student Name");
DataRow dr = dt.NewRow();
dr["Student Id"] = "1";
dr["Student Name"] = "Mahesh";
dt.Rows.Add(dr);
//Include as many rows you need and bound it to the DropDown Lists. I have done it for one DropDownList.
// Method is similar to others also.
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Student Name";
DropDownList1.DataValueField = "Student Id";
DropDownList1.DataBind();
Now this is the most important part.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function DisableOtherDropdowns(obj) {
var currentDropDownId = obj.id;
var currentDropDownText = obj.options[obj.selectedIndex].text;
$('table select').each(function () {
var dropId = this.id;
if (dropId != currentDropDownId) {
this.selectedIndex = 0;
}
});
$('#<%= txtSelectedText.ClientID %>').val(currentDropDownText);
}
</script>
I have included JQuery CDN. In the script, I'm targeting all DropDown
s which are present inside the HTML Table.
When the selection of a DropDownList
changes, this script executes. You can see currentDropDownText
stores the current selected Value of the DropDown
and I'm setting that value to a Text Box simply to see which value is currently selected.
Note
This is really a simple program. There might be other solutions and if you know any, let me know. It is always nice to know more than one approach to solve a problem.