标记一个元素后验证所需的复选框

时间:2018-09-12 20:10:43

标签: javascript jquery twitter-bootstrap

当您拥有一个Bootstrap复选框组并且需要要求用户标记至少一个但不是全部复选框时,该怎么办?

Bootstrap验证(和浏览器)使用“ required”属性来检测它们,但是当多个复选框在组中彼此相关时,显然不是针对此用例。

所以我想使用JavaScript在其他属性上切换属性,但到目前为止我还没有成功。

<div class="checkbox-group">
  <div class="form-check form-checkbox">
    <input type="checkbox" class="form-check-input" id="choice-64" value="64" name="choice-19" required>
    <label class="form-check-label" for="choice-64"> Manzana</label>
  </div>

  <div class="form-check form-checkbox">
    <input type="checkbox" class="form-check-input" id="choice-65" value="65" name="choice-19" required>
    <label class="form-check-label" for="choice-65"> Sandía</label>
  </div>

  <div class="form-check form-checkbox">
    <input type="checkbox" class="form-check-input" id="choice-66" value="66" name="choice-19" required>
    <label class="form-check-label" for="choice-66"> Melón</label>
  </div>
</div>

我在GitHub上找到了此代码,但效果不佳:

$('#myForm .checkbox-group').on('change', 'input[type="checkbox"]', function (e) {
  var $group = $(this)
  var $checkbox = $(e.target)
  $group.not($checkbox).attr('required', !$checkbox.attr('checked'))
})

1 个答案:

答案 0 :(得分:1)

以下代码将更改组中所有复选框的required值,而不仅是其中一个已更改。如果至少选中了一个复选框,它将全部设置为false,否则设置为true

$('#myForm .checkbox-group').on('change', 'input[type="checkbox"]', function (e) {
  var $checkbox = $(this)
  var $group = $checkbox.parents('.checkbox-group')
  var checkedItems = $('input[type="checkbox"]:checked').length
  $('input[type=checkbox]', $group).attr('required', checkedItems === 0)
})

如果您将它们全部切换而不是跳过更改的内容,将使其更易于处理。 在这里尝试:https://jsfiddle.net/buqrn7mt/