限制选中的复选框功能无法按预期工作

时间:2019-02-08 08:46:30

标签: html typescript checkbox

我试图在我的复选框问题中实现一个功能,该功能中只能选中3个复选框。但是,它将继续检查超出限制(3)的地方。

我确定与 latestcheck.checked = false;

有关

我的打字稿功能:

factors(whichlist, maxchecked, latestcheck) {
// An array containing the id of each checkbox to monitor. 
var listone = new Array("teamStrength", "marketOp", "productOff", "technology", "financialPerform", "coinvestors", "mediaExpo", "awardsWon", "portfolioFit");

// End of customization.
var iterationlist;
eval("iterationlist=" + whichlist);
var count = 0;
for (var i = 0; i < iterationlist.length; i++) {
  if ((<HTMLInputElement>document.getElementById(iterationlist[i])).checked == true) { 
    count++;

  }
  if (count > maxchecked) { 
    latestcheck.checked = false; 
    console.log("last checked: " + latestcheck.checked); 
  }
}
if (count > maxchecked) {
  alert('Sorry, only ' + maxchecked + ' may be checked.');
}

}

需要发生的是,在警报弹出后,我选中的复选框(限制为3,因此第四个复选框未选中)。

1 个答案:

答案 0 :(得分:1)

您不能这样做吗? (我不使用TypeScript)

const listOne = ["teamStrength", "marketOp", "productOff", "technology", "financialPerform", "coinvestors", "mediaExpo", "awardsWon", "portfolioFit"];    
const container = document.getElementById("checkboxContainer");
container.addEventListener("click",function(e) {
  if (listOne.indexOf(e.target.id) !=-1) { // may not even be needed
    if (container.querySelectorAll("input[type=checkbox]:checked").length > 3) {
      e.preventDefault(); // or this.checked=false;
    }
  }
});

简体:

document.querySelectorAll(".question").forEach(function(q) {
  q.addEventListener("click", function(e) {
    var len = this.querySelectorAll("input[type=checkbox]:checked").length;
    if (len > 3) {
      e.preventDefault();
    }
  });
});
<div class="question">
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
</div>
<div class="question">
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
</div>