当使用支持HTML5的新浏览器时(例如FireFox 4); 表单字段有required='required'属性; 表单字段为空/空白; 然后点击提交按钮; 浏览器检测到“required”字段为空,不提交表单;相反,浏览器显示一个提示,要求用户在字段中输入文本。

现在,我有了一组复选框,而不是单一的文本字段,其中至少有一个应该由用户选中/选择。

如何在这组复选框上使用HTML5 required属性? (因为只有一个复选框需要被选中,我不能把所需的属性放在每个复选框上)

ps.我使用simple_form,如果这很重要。


更新

HTML 5的多重属性在这里有用吗?以前有人用它来做类似我的问题吗?

更新

HTML5规范似乎不支持这个特性:ISSUE-111:什么是输入?@type =复选框的@required mean ?

(发行状态:发行已被标记为已关闭。) 下面是解释。

更新2

这是一个老问题,但我想澄清的是,这个问题的最初意图是能够在不使用Javascript的情况下完成上述工作——即使用HTML5的方式来完成。回想起来,我应该更明显地说明“没有Javascript”。


当前回答

纯JS解决方案:

const group = document.querySelectorAll('[name="myCheckboxGroup"]');

function requireLeastOneChecked() {
    var atLeastOneChecked = false;
    for (i = 0; i < group.length; i++)
        if (group[i].checked)
            atLeastOneChecked = true;
    if (atLeastOneChecked)
        for (i = 0; i < group.length; i++)
            group[i].required = false;
    else
        for (i = 0; i < group.length; i++)
            group[i].required = true;
}
requireLeastOneChecked(); // onload

group.forEach(function ($el) {
    $el.addEventListener('click', function () { requireLeastOneChecked(); })
});

其他回答

一个通用的解决方案,无需更改提交事件或知道复选框的名称

构建一个函数,将复选框标记为HTML5-Invalid 扩展Change-Event并在开始时检查有效性

jQuery.fn.getSiblingsCheckboxes = function () { let $this = $(this); let $parent = $this.closest('form, .your-checkbox-listwrapper'); return $parent.find('input[type="checkbox"][name="' + $this.attr('name')+'"]').filter('*[required], *[data-required]'); } jQuery.fn.checkRequiredInputs = function() { return this.each(function() { let $this = $(this); let $parent = $this.closest('form, .your-checkbox-list-wrapper'); let $allInputs = $this.getSiblingsCheckboxes(); if ($allInputs.filter(':checked').length > 0) { $allInputs.each(function() { // this.setCustomValidity(''); // not needed $(this).removeAttr('required'); $(this).closest('li').css('color', 'green'); // for debugging only }); } else { $allInputs.each(function() { // this.reportValidity(); // not needed $(this).attr('required', 'required'); $(this).closest('li').css('color', 'red'); // for debugging only }); } return true; }); }; $(document).ready(function() { $('input[type="checkbox"][required="required"], input[type="checkbox"][required]').not('*[data-required]').not('*[disabled]').each(function() { let $input = $(this); let $allInputs = $input.getSiblingsCheckboxes(); $input.attr('data-required', 'required'); $input.removeAttr('required'); $input.on('change', function(event) { $input.checkRequiredInputs(); }); }); $('input[type="checkbox"][data-required="required"]').checkRequiredInputs(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> </head> <form> <ul> <li><input type="checkbox" id="checkbox1" name="countries" value="Argentina" required="required">Argentina</li> <li><input type="checkbox" id="checkbox2" name="countries" value="France" required="required">France</li> <li><input type="checkbox" id="checkbox3" name="countries" value="Germany" required="required">Germany</li> <li><input type="checkbox" id="checkbox4" name="countries" value="Japan" required="required">Japan</li> <li><input type="checkbox" id="checkbox5" name="countries" value="Australia" required="required">Australia</li> </ul> <input type="submit" value="Submit"> </form>

纯JS解决方案:

const group = document.querySelectorAll('[name="myCheckboxGroup"]');

function requireLeastOneChecked() {
    var atLeastOneChecked = false;
    for (i = 0; i < group.length; i++)
        if (group[i].checked)
            atLeastOneChecked = true;
    if (atLeastOneChecked)
        for (i = 0; i < group.length; i++)
            group[i].required = false;
    else
        for (i = 0; i < group.length; i++)
            group[i].required = true;
}
requireLeastOneChecked(); // onload

group.forEach(function ($el) {
    $el.addEventListener('click', function () { requireLeastOneChecked(); })
});

我也遇到过同样的问题,我的解决方案是这样的:

HTML:

<form id="processForm.php" action="post">
  <div class="input check_boxes required wish_payment_type">
    <div class="wish_payment_type">
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_1">
        <input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
      </label>
    </span>
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_2">
        <input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
      </label>
    </span>
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_3">
        <input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz
      </label>
          
      <input id='submit' type="submit" value="Submit">
  </div>
</form>

JS:

var verifyPaymentType = function () {
  var checkboxes = $('.wish_payment_type .checkbox');
  var inputs = checkboxes.find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
}

$('#submit').click(verifyPaymentType);

https://jsfiddle.net/oywLo5z4/

不幸的是,HTML5并没有提供一种开箱即用的方法来做到这一点。

但是,使用jQuery,您可以轻松控制复选框组是否至少有一个选中元素。

考虑下面的DOM片段:

<div class="checkbox-group required">
    <input type="checkbox" name="checkbox_name[]">
    <input type="checkbox" name="checkbox_name[]">
    <input type="checkbox" name="checkbox_name[]">
    <input type="checkbox" name="checkbox_name[]">
</div>

你可以用这个表达:

$('div.checkbox-group.required :checkbox:checked').length > 0

如果至少选中一个元素,则返回true。 在此基础上,您可以实现验证检查。

HTML5并不直接支持在一个复选框组中只选中一个/至少一个复选框。下面是我使用Javascript的解决方案:

HTML

<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two

JAVASCRIPT

function deRequireCb(elClass) {
  el = document.getElementsByClassName(elClass);

  var atLeastOneChecked = false; //at least one cb is checked
  for (i = 0; i < el.length; i++) {
    if (el[i].checked === true) {
      atLeastOneChecked = true;
    }
  }

  if (atLeastOneChecked === true) {
    for (i = 0; i < el.length; i++) {
      el[i].required = false;
    }
  } else {
    for (i = 0; i < el.length; i++) {
      el[i].required = true;
    }
  }
}

javascript将确保至少选中一个复选框,然后取消对整个复选框组的要求。如果选中的复选框变为未选中,那么它将再次需要所有的复选框!