如何检查在一组具有不同名称值的复选框中是否选中了至少一个复选框

the*_*pio 5 html validation checkbox jquery

我有一个问题,我一直在寻找一段时间的答案,但无法让它发挥作用.

我正在寻找一种方法来检查是否选中了一组复选框中的至少一个复选框.让我这么难的原因是这些输入中的每一个都有不同的名称值.我只找到了jQuery验证插件等的答案.这是我的html:

<tr class="formField-checkbox formFieldRequired">
  <td class="formLabelHolder"><label for="field129">Group of checkboxes</label></td>
  <td class="formFieldHolder">
    <input type="checkbox" name="field129[0]" class="formCheckbox required" value="Something1"> 
    <label><span class="formCheckboxLabel">Something1</span></label>
    <input type="checkbox" name="field129[1]" class="formCheckbox required" value="Something2"> 
    <label><span class="formCheckboxLabel">Something2</span></label>
    <input type="checkbox" name="field129[2]" class="formCheckbox required" value="Something3"> 
    <label><span class="formCheckboxLabel">Something3</span></label>
  </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

这是我现在的jQuery:

// Validate all checkboxes
var named = [];
var $requiredCheck = $(this).find('input[type="checkbox"].required');

$($requiredCheck,$formId).each(function() {
  // Creates an array with the names of all the different checkbox group.
  named[$(this).attr('name')] = true;
});

// Goes through all the names and make sure there's at least one checked.
for (name in named) {
  var $checkboxes = $("input[name='" + name + "']");
  if ($checkboxes.filter(':checked').length == 0) {
    $checkboxes.closest('.formFieldHolder').addClass('error').append('<span   class="error">Required!</span>');
  } 
}
Run Code Online (Sandbox Code Playgroud)

这显然在目前并不完美,因为复选框具有不同的名称值.现在,append打印出与复选框一样多的错误消息.例如,如果有五个复选框,并且选中了一个复选框,则仍会提供四次错误消息.我已经尝试过这么长时间解决这个问题,但根本无法做到这一点.我无法更改这些复选框的名称值,或者只是对html执行任何操作.我认为可以做到的一种方法是删除名称中的最后[0],[1]和[2]部分但我找不到如何让它工作的方法.

我认为简单的jQuery验证方法会失败,因为可能有更多的复选框组,而不是单个表单中的一个.下一组复选框的名称值为name ="field130 [0]",name ="field130 [1]"和name ="field130 [2]".我希望你能明白我的观点.

任何帮助将非常感激.

编辑:

添加了一个表单中可能有多个复选框组的说明

Nic*_*ick 10

你这样做太复杂了:)

if ($('.required:checked').length > 0) {  // the "> 0" part is unnecessary, actually
    [do something]
}
Run Code Online (Sandbox Code Playgroud)

请参阅官方jQuery API页面上的第一个示例:checked.

回应你的评论

如果页面上有多个表单,则可以将表单指定为容器:

if ($('#form1_id').find('.required:checked').length) {...
Run Code Online (Sandbox Code Playgroud)

测试多种形式

给每个表格一个班级testable_form.

$('.testable_form').each(function() {
    if ($(this).find('.required:checked').length) {
        [do something - set a flag, add a class...]
    }
});
Run Code Online (Sandbox Code Playgroud)