如何将复选框列表选择限制为最多 4 个,并且在第 5 个选择时它应该只清除第 5 个选定的项目

how to restrict checkboxlist selection up to 4 and on 5th selection it should clear only 5th selected item

我需要创建复选框列表,它应该 select 最多 4 个项目。 如果用户 select 第 5 项,那么它应该只清除特定的第 5 项。 目前此代码总是清除复选框列表的第一项。

这是我的 C#:

 protected void lstSalesPerson_SelectedIndexChanged(object sender, EventArgs e)
    {
        var items = from ListItem li in lstSalesPerson.Items
                    where li.Selected == true
                    select li;

        Label1.Text = "";



        for (int i = 0; i < lstSalesPerson.Items.Count; i++)
        {

            if (lstSalesPerson.Items[i].Selected == true)
            {
                if (items.Count() > 4)
                {
                    Label1.Text = "checked maximum 4 items.";                      
                    lstSalesPerson.Items[i].Selected = false;
                }
            }
        }           
    }

这是我的 html:

<asp:ListBox ID="lstSalesPerson" runat="server" SelectionMode="Multiple" AutoPostBack="true" OnSelectedIndexChanged="lstSalesPerson_SelectedIndexChanged">                                                    </asp:ListBox>

您应该按如下方式反转循环。在你的循环中,它从 index[0] 开始,并检查所选项目的总数是否 >4 如果正确,它将使第一个项目为 false。

所以循环应该来自反向索引。因此,如果选择了 5 个项目,那么选择的第一个索引将是 [4],它将得到 false

试试下面的代码

for (int i = lstSalesPerson.Items.Count-1; i >=0 ; i--)
{

            if (lstSalesPerson.Items[i].Selected == true)
            {
                if (items.Count() > 4)
                {
                    Label1.Text = "checked maximum 4 items.";                      
                    lstSalesPerson.Items[i].Selected = false;
                }
            }
        }  

我使用 javascript 找到答案如下: 这可能对某人有所帮助:我正在使用此控件 .multiselect-container > li > a > label > input 因为我的控件是在模板设计中使用这种方式呈现的。但是您可以将逻辑用于您的代码。谢谢

  $('.multiselect-container > li > a > label > input').click(function (e) {              
            var ddl = document.getElementById("<%=lstSalesPerson.ClientID%>");               
            if ($(this).prop('checked')) {                   
                var count = 0;                    
                for (var i = 0; i < ddl.options.length; i++) {
                        if (ddl.options[i].selected) {
                            count++; 
                            if (count > 3) {                                   
                                $(this).removeAttr('checked');
                   $(this).parent().parent().parent().prop('checked', false);
                   $(this).parent().parent().parent().prop('clicked', false);
                   $(this).parent().parent().parent().removeClass('active');
                                alert("You can select Max 4 sales person.");
                                return false;
                            } 
                        }
                }


            }
        });