没有工作限制选中的复选框功能如预期

问题描述 投票:0回答:1

我试图实现一个功能到我的复选框问题,其中只有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极限之后,所以第四个检查框),将取消选中。

html typescript checkbox
1个回答
1
投票

你能不能做到这一点? (我不这样做打字稿)

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>
© www.soinside.com 2019 - 2024. All rights reserved.