.Net Make CheckBox List act like RadioButtons

I had a site that I wanted to add a list of checkboxes but I wanted them to act like radiobuttons, which means I wanted the user to only be able to check one box and the others would clear out.

thanks to Mudassar Khan at aspsnippets.com he shows how this can be done with the .net checkboxlist and javascript.

<script type = "text/javascript">

    function MutExChkList(chk)

    {

        var chkList = chk.parentNode.parentNode.parentNode;

        var chks = chkList.getElementsByTagName("input");

        for(var i=0;i<chks.length;i++)

        {

            if(chks[i] != chk && chk.checked)

            {

                chks[i].checked=false;

            }

        }

    }

</script>

And then add the checkboxlist

<asp:CheckBoxList ID="CheckBoxList1" runat="server">

    <asp:ListItem Text = "1" Value = "1" onclick = "MutExChkList(this);">

    </asp:ListItem>

    <asp:ListItem Text = "2" Value = "2" onclick = "MutExChkList(this);">

    </asp:ListItem>

    <asp:ListItem Text = "3" Value = "3" onclick = "MutExChkList(this);">

    </asp:ListItem>

    <asp:ListItem Text = "4" Value = "4" onclick = "MutExChkList(this);">

    </asp:ListItem>

    <asp:ListItem Text = "5" Value = "5" onclick = "MutExChkList(this);">

    </asp:ListItem>

</asp:CheckBoxList>

The problem I ran into was I added a submit button to my site to email the response to myself, if a user chooses nothing you get an null error. I tried many different and usual ways to test for null or nothing but ended up going a little different.

I added one more line to the checkboxlist but made it equle none or nothing and made it not visible. This way when I get emailed it will show me none were choosen or you can go an extra step and code that if SelectedValue = “none” the user receives an error to chose one box.

<asp:ListItem Value="none" Selected="True" style="display:none" onclick = "MutExChkList(this);">None</asp:ListItem>

Technorati Tags: ,

     

Leave a Reply