locked
How I de-select last check in Javascript RRS feed

  • Question

  • User-582711651 posted

    Hi friends, 

    I want to allow 2 checkbox=checked, if user clicks 3rd check then the last check should uncheck, here I prepared but getting minor mistake, how I fix it.

    ref my code: 

    <asp:CheckBoxList ID="CBL_DD" runat="server" RepeatDirection="Horizontal" onchange="return Validate()">                                                                                                                <asp:ListItem Text="D1" Value="1" />                                                                                                              <asp:ListItem Text="D2" Value="2" />                                                                                                               <asp:ListItem Text="D3" Value="3" />                                                                                                               <asp:ListItem Text="D4" Value="4" />                                                                                                              <asp:ListItem Text="D5" Value="5" />                                                                                                          </asp:CheckBoxList></td>
    
        <script language="javascript" type="text/javascript">
        function Validate() {
            var chk = document.getElementById("<%=CBL_DD.ClientID%>");
            var checkbox = chk.getElementsByTagName("input");
            var counter = 0;
            for (var i = 0; i < checkbox.length; i++) {
                if (checkbox[i].checked) {
                    counter++;                            
                    var x = i            
                }
            }
            if (counter > 2) {
                checkbox[x].checked = false;
                alert("Sorry! You can select maximum 2 checkboxes");
                return false;
            }
            else {
                return true;
            }
            
        }
    </script>

    Thanks in advance. 

    Sunday, May 30, 2021 5:55 PM

Answers

  • User-582711651 posted

    Hi KathyW,

    Sorry, nothing, it works well. 

    Thanks.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 31, 2021 1:08 AM

All replies

  • User409696431 posted

    " getting minor mistake"

    What is the mistake you are getting?

    Sunday, May 30, 2021 6:59 PM
  • User-582711651 posted

    Hi KathyW,

    Sorry, nothing, it works well. 

    Thanks.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 31, 2021 1:08 AM