jQuery:如何仅禁用复选框

问题描述

我正在使用下面在网站上找到的代码,它可以正常工作。

我有一个由单选按钮和复选框组成的25个问题测验。

如果在同一页面上我同时具有单选按钮和复选框,则出问题了。下面的代码将这两个都计算在内,但我只希望它计算已打勾的复选框。

  • 目前,一旦我达到最大答案,我将无法回答其余的单选按钮问题;反之亦然,复选框前的单选按钮将计入最大答案数。
  • 代码还同时禁用了单选按钮和复选框,因此我想找到一种方法使其仅禁用复选框。

我可以将代码分割成更多的div,但这将变得非常复杂,因为我的jQuery使用div控制测验的流程:

$(document).ready(function () {
  $("input[type=checkBox]").click(function (e) {
    if ($(e.currentTarget).closest("div.question").length > 0) {
      disableInputs($(e.currentTarget).closest("div.question")[0]);        
    }
  });
});

function disableInputs(questionElement) {
  console.log(questionElement);
  if ($(questionElement).data('max-answers') == undefined) {
    return true;
  } else {
    maxAnswers = parseInt($(questionElement).data('max-answers'),10); 
    if ($(questionElement).find(":checked").length >= maxAnswers) {
      $(questionElement).find(":not(:checked)").attr("disabled",true);
    } else {
      $(questionElement).find("input[type=checkBox]").attr("disabled",false);
    }
  }
}

这是主要测验的摘要

<div class="Q8 question" data-max-answers="3">
  <h2>Access Control Questions</h2><br>

  <strong>Is it ok to share the door access code?</strong><br>
  <input type="radio" id="ac1" name="access1" value="0">Yes<br>
  <input type="radio" id="ac2" name="access1" value="1">No<br><br>
  <br><strong><label for="access1">From the list below select those that are the aims of an Access Control System (Maximum of 3) </strong></span></label><br>
  <input type="checkBox" id="ac3" name="access"  value="1" /> To ensure only authorised users have access to our systems</p>
  <input type="checkBox" id="ac4" name="access"  value="1" /> To protect physical access to our offices</p>
  <input type="checkBox" id="ac4a" name="access" value="0" /> To give you access to other users passwords</p>
  <input type="checkBox" id="ac5" name="access"  value="1" /> To ensure users have access to systems they require access too</p>

  <br><strong>A client is visiting and asks to use your computer,what should you do?</strong><br>
  <input type="radio" id="ac6" name="access5" value="0">Let them use your computer because they are a client so can do what they wish<br>
  <input type="radio" id="ac7" name="access5" value="1">Politely say you are not allowed to do that and refer them to the manager they have come to visit<br>
  <input type="radio" id="ac8" name="access5" value="0">Pretend to be on a call and hope they go away<br><br>
</div>

<div class="Q8a">
  <input id="Q8PrevBut" type="button" Value="Back"> 
  <input id="Q8NextBut" type="button" Value="Next"> 
</div>

解决方法

我认为:not(:checked)会同时返回单选按钮和复选框。您可以尝试通过添加input[type=checkbox]使选择器更具体,请参见下文:

if ($(questionElement).find("input[type=checkbox]:checked").length >= maxAnswers)

...并在禁用复选框时执行相同的操作:

$(questionElement).find("input[type=checkbox]:not(:checked)").attr("disabled",true);