我正在尝试制作一个将隐藏并显示表单某些部分的表单。在某些尝试中它可以正常工作。但是,当用户选择并检查了显示为BadField的badCheckbox类的选项时,则用户检查了未显示为BadField的“ badField”类而不显示badField的选项,但该选项仍未隐藏。

并且当用户尝试单独检查选项时,所有选项仅在上述情况下才能正常工作。

有什么办法吗?



//Script to hide and show div
$('.badCheckbox').change(function() {
  let checked = 0;
  $('.badCheckbox').each(function() {
    if (this.checked) {
      checked += 1;
    }
  });
  if (checked != 0) {
    $('#badField').show();
    $('#goodField').hide();
  } else {
    $('#badField').hide();
    $('#goodField').show();
  }
});

//script to check only one of three
$(".oneChecked").on('click', function() {
  // in the handler, 'this' refers to the box clicked on
  var $box = $(this);
  if ($box.is(":checked")) {
    var group = "input:checkbox[name='" + $box.attr("name") + "']";
    $(group).prop("checked", false);
    $box.prop("checked", true);
  } else {
    $box.prop("checked", false);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />

<div id="badField" style="display:none;">
  <p>:((</p>
  <input type="submit" />
</div>

<div id="goodField">
  <p>NICE!!!</p>
  <input type="submit" />
</div>

最佳答案

考虑以下改进。



$(function() {
  function checkStuff(checked) {
    if (checked) {
      $('#badField').show();
      $('#goodField').hide();
    } else {
      $('#badField').hide();
      $('#goodField').show();
    }
  }

  //script to check only one of three
  $(".boxes").on('change', ".oneChecked", function() {
    if ($(this).is(":checked")) {
      $(".boxes input[type='checkbox']").prop("checked", false);
      $(this).prop("checked", true);
      checkStuff($(this).is(".badCheckbox"));
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boxes">
  <input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
  <input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
  <input name="checkin" type="checkbox" class="oneChecked" />
</div>

<div id="badField" style="display:none;">
  <p>:((</p>
  <input type="submit" />
</div>

<div id="goodField">
  <p>NICE!!!</p>
  <input type="submit" />
</div>

07-28 05:14