Allow only one checkbox to be checked

Joined
Jan 13, 2023
Messages
10
Reaction score
1
Hi,
I have a panel with checkboxes:

ASP.net:
<asp:Panel runat="server" ID="pnlMyPanel" GroupingText="My Panel Test" Visible="false">

  <div class="DetailsBoxSetting">
    <asp:CheckBox ID="chk_One" runat="server" CssClass="chk" />
    <asp:Label ID="lbl_one" CssClass="StandardLabel" runat="server">One</asp:Label>
  </div>  
                              
  <div class="DetailsBoxSetting">
    <asp:CheckBox ID="chk_Two" runat="server" CssClass="chk" />
    <asp:Label ID="lbl_Two" CssClass="StandardLabel" runat="server">Two</asp:Label>
  </div> 
                               
</asp:Panel>

I want to allow only one checkbox to be checked .
How do I do that ?
Thank you
 
Joined
Mar 5, 2023
Messages
36
Reaction score
12
You can achieve this by using a bit of JavaScript/jQuery code. Here's an example:

Add the following code to the page, after the panel:

HTML:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
  $('#<%= pnlMyPanel.ClientID %> input[type="checkbox"]').on('change', function() {
    if ($(this).is(':checked')) {
      $('#<%= pnlMyPanel.ClientID %> input[type="checkbox"]').not(this).prop('checked', false);
    }
  });
});
</script>

This code attaches a change event handler to all checkboxes inside the panel. Whenever a checkbox is checked, it unchecks all other checkboxes in the same panel.

Note that this code requires jQuery. If you're not already using it on your page, you'll need to add it. You can do this by adding the following line to the head section of your page:

HTML:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Alternatively, you can download jQuery and include it in your project.

Hope this helps!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top