How to create Checkboxes that act like Radio buttons with Jquery

Posted by hmloo on Geeks with Blogs See other posts from Geeks with Blogs or by hmloo
Published on Fri, 23 Mar 2012 00:22:47 GMT Indexed on 2012/03/23 5:30 UTC
Read the original article Hit count: 380

Filed under:

I have a post here to show code examples for check/uncheck all checkbox with Jquery. This time I will implement another request that the user should only be able to check at most one of the checkboxes, it's behave like radio buttons.

There are 2 cases. Case 1 shows function that has little difference with radio button. It allows the user to deselect checkbox. Case 2 is same as radio button.

Case 1

<head id="Head1" runat="server"> 
    <title></title> 
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> 
    <style type="text/css"> 
           .cbRowItem {display:block;} 
     </style> 
    <script type="text/javascript"> 
    $(document).ready(function() 
    { 
        var $chk = $('input:checkbox .cbRowItem'); 
        $chk.click(function() 
        { 
            $chk.not(this).removeAttr('checked'); 
        }); 
    }); 
  </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div style="display:block;"> 
    <asp:CheckBox id="CheckBox1" runat="server" class="cbRowItem" Text = "CheckBox 1"/> 
    <asp:CheckBox id="CheckBox2" runat="server" class="cbRowItem" Text = "CheckBox 2"/> 
    <asp:CheckBox id="CheckBox3" runat="server" class="cbRowItem" Text = "CheckBox 3"/> 
    <asp:CheckBox id="CheckBox4" runat="server" class="cbRowItem" Text = "CheckBox 4"/> 
    </div> 
    </form> 
</body> 
</html>

Case 2

<head id="Head1" runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <style type="text/css">
           .cbRowItem {display:block;}
     </style>
    <script type="text/javascript">
    $(document).ready(function()
    {
        var $chk = $('input:checkbox .cbRowItem'); 
        $chk.click(function()
        {
            $chk.removeAttr('checked');
            $(this).attr('checked', 'checked');
        });
    });
  </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="display:block;">
    <asp:CheckBox id="CheckBox1" runat="server" class="cbRowItem" Text = "CheckBox 1"/>
    <asp:CheckBox id="CheckBox2" runat="server" class="cbRowItem" Text = "CheckBox 2"/>
    <asp:CheckBox id="CheckBox3" runat="server" class="cbRowItem" Text = "CheckBox 3"/>
    <asp:CheckBox id="CheckBox4" runat="server" class="cbRowItem" Text = "CheckBox 4"/>
    </div>
    </form>
</body>
</html>

© Geeks with Blogs or respective owner