2017-07-18 42 views
0

我使用CheckBoxList來顯示一組業務單位。我想限制選擇最多5個項目,並且如果用戶選擇第6個項目,那麼我應該顯示一個警報並取消選擇第6個項目。CheckBoxList - 將選擇限制到特定數字

的控制是如下:我使用

<asp:CheckBoxList ID="ckBLBusinessUnits" onclick="loader(this.id);" runat="server" AutoPostBack="True" Visible="false" OnSelectedIndexChanged="ckBLBusinessUnits_SelectedIndexChanged"></asp:CheckBoxList> 

JS功能是:

function loader(controlID) { 
    modal = document.getElementById('loadingImage'); 
    modal.style.display = "block"; 

    if (controlID == "ckBLBusinessUnits") 
    { 
     if (($('#ckBLBusinessUnits :checkbox:checked').length) > 5) 
     { 
      alert("Max 5 BU's can be selected"); 
//is it possible to uncheck here? I am unable to find any method to do so. 
     } 
    } 
} 

C#是如下:

protected void ckBLBusinessUnits_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      if (selectedValues.Count <= 5) 
      { 
       //Do something and then disable the loader. 
       loadingImage.Style.Add("display", "none"); 
      } 
      else if (selectedValues.Count > 5) 
      { 
       //is it possible to uncheck here? I am unable to find any method to do so. 
      } 

     } 

回答

0

這可能不是你問什麼,但它可能適用於你的情況。無需取消選中複選框,只要所選項目總數爲5,就禁用其他複選框,並顯示警報。

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     List<ListItem> SelectedItems = new List<ListItem>(); 

     foreach (ListItem ItemsSelected in CheckBoxList1.Items) 
     { 
      if (ItemsSelected.Selected) 
       SelectedItems.Add(ItemsSelected); 
     } 

     if(SelectedItems.Count() == 5) 
     { 
      // Display alert 

      foreach(ListItem item in CheckBoxList1.Items) 
      { 
       if(!SelectedItems.Contains(item)) 
       { 
        item.Enabled = false; 
       } 
      } 
     } else 
     { 
      foreach (ListItem item in CheckBoxList1.Items) 
      { 
       item.Enabled = true; 
      } 
     } 
}