jQuery: как отключить только флажки

#javascript #jquery #checkbox #disable

#javascript #jquery #флажок #отключить

Вопрос:

Я использую приведенный ниже код, который я нашел на веб-сайте, и он отлично работает.

У меня есть тест на 25 вопросов, состоящий из переключателей и флажков.

Если на одной странице у меня есть как переключатели, так и флажки, что-то идет не так. Приведенный ниже код учитывает оба этих параметра, но я хочу, чтобы он учитывал только отмеченные флажки.

  • В настоящее время, как только я набираю максимальное количество ответов, я не могу ответить на оставшиеся вопросы с переключателями; или наоборот, переключатели перед флажками учитывают максимальное количество ответов.
  • Код также отключает как переключатели, так и флажки, поэтому я хотел бы найти способ отключить только флажки.

Я мог бы разделить код на еще большее количество разделов, но это станет очень сложным, поскольку мой jQuery управляет ходом теста с использованием разделов:

 $(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>
  

Ответ №1:

Я думаю, :not(:checked) возвращает как переключатели, так и флажки. Вы могли бы попытаться сделать селектор более конкретным, добавив input[type=checkbox] , см. Ниже:

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

…и сделайте то же самое при отключении флажков:

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

Комментарии:

1. Потрясающе! Не были бы вы так любезны пометить ответ как принятый? Будущие посетители могут извлечь из этого пользу