Click here to Skip to main content
15,886,046 members
Articles / Web Development / ASP.NET / ASP.NET2.0
Tip/Trick

CheckBoxList acts like RadioButtonList

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
3 Jan 2013CPOL 17.3K   1   1
Checkboxes working like radio buttons.

Introduction

This article is about how to use CheckBoxList to work like RadioButtons using JavaScript.

Using the code

Just place the code given below in the head section of your .ASPX page:

JavaScript
<script type="text/javascript" language="javascript">
    function SetChkBx(event) {
        var chkBoxCount = document.getElementById('<%= chkList1.ClientID %>').getElementsByTagName("input");
        for (i = 0; i < chkBoxCount.length; i++) {
            if (chkBoxCount[i].type == 'checkbox')
                chkBoxCount[i].checked = false;
        }
        if (event.target == null) {
            event.srcElement.checked = true;
            alert("You selected " + event.srcElement.value);
        }
        else {
            event.target.checked = true;
            alert("You selected " + event.target.value);
        }
    }
</script>

Points of Interest 

Here is the code, event.target is used which is always null for IExplorer. event.srcElement is used in IExplorer which tell the browser about the source element and and event.target is not null for other browsers. So for other browsers we we use this.

Place the below tag under your <Form> tag.

XML
<asp:CheckBoxList ID="chkList1" runat="server" RepeatDirection="Vertical" 
    RepeatLayout="Flow" OnClick="javascript:SetChkBx(event);">
    <asp:ListItem>Apple</asp:ListItem>
    <asp:ListItem>Mango</asp:ListItem>
    <asp:ListItem>Banana</asp:ListItem>
    <asp:ListItem>Guava</asp:ListItem>
    <asp:ListItem>Grapes</asp:ListItem>
</asp:CheckBoxList>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
sandeepkumarvemula11-Feb-13 22:28
sandeepkumarvemula11-Feb-13 22:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.