我有一个问题,一直在寻找答案,但是一直无法解决。
我正在寻找一种方法来检查一组复选框中是否至少有一个被选中。让我感到困难的是,每个输入框都具有不同的名称值。我只找到了适用于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>
这是我现在所用的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>');
}
}
目前这种方法显然不完美,因为复选框具有不同的名称值。现在追加打印出与复选框数量相同的错误消息。例如,如果有五个复选框并且选中一个,它仍然会四次给出错误消息。我已经尝试自己解决这个问题很长时间了,但是简单地无法解决。我不能更改这些复选框的名称值或者干脆对html做任何事情。我想到的一种方法是删除名称中的最后一个[0]、[1]和[2]部分,但我没有找到如何使其正常工作的方法。
我认为简单的jQuery验证方法将失败,因为单个表单中可能会有多个复选框组。下一组复选框将具有名称值name="field130[0]"、name="field130[1]"和name="field130[2]"。我想你明白我的意思,希望如此。
非常感谢您的任何帮助。
编辑:
添加了描述,说明一个表单中可能有多个复选框组。
> 0
。这似乎是不必要的。否则就点赞了。 - Popnoodles