Allow only one selection of CheckBoxList in ASP.NET using JavaScript


A CheckBoxList is a list of checkboxes grouped together under one control. It’s used to provide to the end user the ability to select multiple items for one property, such as selecting a list of desired places to work. But, what If you want your CheckBoxList to only allow one selecting? It’s quite easy to achieve that by using JavaScript.

In this tutorial, I will explain in details how to limit the selection of CheckBoxList item to one. First, let’s create a checkbox list and add a few items to it.

HTML

<div>

        <b>Where would you like to retire?</b>
        <asp:CheckBoxList ID="myCheckBoxList" runat="server">
            <asp:ListItem Text="Bahamas" Value="Bahamas" onclick="CheckOnlyOneCheckBox(this);" />
            <asp:ListItem Text="Florida" Value="Florida" onclick="CheckOnlyOneCheckBox(this);" />
            <asp:ListItem Text="Hawaii" Value="Hawaii" onclick="CheckOnlyOneCheckBox(this);" />
            <asp:ListItem Text="Thailand" Value="Thailand" onclick="CheckOnlyOneCheckBox(this);" />
            <asp:ListItem Text="Vermont" Value="Vermont" onclick="CheckOnlyOneCheckBox(this);" />
        </asp:CheckBoxList>
    </div>

Now, copy the JavaScript function below into your markup or in a separate JavaScript file. This function takes a checkbox item as an argument, then uncheck all other checkboxes within the CheckBoxList using a loop.

JavaScript

    <script type="text/javascript">
        function CheckOnlyOneCheckBox(checkbox) 
		{
            var checkBoxList = checkbox.parentNode.parentNode.parentNode;
            var list = checkBoxList.getElementsByTagName("input");
            for (var i = 0; i < list.length; i++) 
			{
                if (list[i] != checkbox && checkbox.checked) 
				{
                    list[i].checked = false;
                }
            }
        }
    </script> 

Run the application

Allow only one selection of CheckBoxList in ASP.NET

Related Articles

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply