How to make a CheckBoxList items single select in Asp.Net

Introduction:

In this article I am going to explain how to make a CheckBoxList single select in asp.net

Description:

Usually RadioButtonList is the control which allow the user to select a single selection of items inside it and users will use CheckBoxList control to allow multiple selection of items. However in some cases we need to make the CheckBoxList control a single select one. You can make use of Javascript to achieve this.

The logic here is to attach a Javascript function in onclick event of each items in CheckboxList.

Javascript Function

<script type = "text/javascript">
            function UncheckOthers(objchkbox) {
                //Get the parent control of checkbox which is the checkbox list
                var objchkList = objchkbox.parentNode.parentNode.parentNode;
                //Get the checkbox controls in checkboxlist
                var chkboxControls = objchkList.getElementsByTagName("input");
                //Loop through each check box controls
                for (var i = 0; i < chkboxControls.length; i++) {
                    //Check the current checkbox is not the one user selected
                    if (chkboxControls[i] != objchkbox && objchkbox.checked) {
                        //Uncheck all other checkboxes
                        chkboxControls[i].checked = false;
                    }
                }
            }
</script>

HTML:

 <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Text="FirstValue" Value="1" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Second Value" Value="2" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Third Value" Value="3" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Fourth Value" Value="4" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Fifth Value" Value="5" onclick="UncheckOthers(this);">
            </asp:ListItem>
</asp:CheckBoxList>

Demo

Advertisements

, , ,

  1. #1 by SutoCom on May 29, 2015 - 11:03 am

    Reblogged this on SutoCom Solutions.

    Like

  2. #2 by RAbab on April 25, 2016 - 5:42 am

    Thanks, this is what I exactly need (y)

    Like

  3. #3 by KODEESWARAN T on September 18, 2016 - 9:49 am

    Thanks. good one

    Like

  4. #4 by lovely on October 4, 2017 - 3:59 am

    Thank you so much. Its works for me…

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: