大佬教程收集整理的这篇文章主要介绍了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>
这是我现在的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>'); } }
这显然在目前并不完美,因为复选框具有不同的名称值.现在,append打印出与复选框一样多的错误消息.例如,如果有五个复选框,并且选中了一个复选框,则仍会提供四次错误消息.我已经尝试过这么长时间解决这个问题,但根本无法做到这一点.我无法更改这些复选框的名称值,或者只是对html执行任何操作.我认为可以做到的一种方法是删除名称中的最后[0],[1]和[2]部分但我找不到如何让它工作的方法.
我认为简单的jQuery验证方法会失败,因为可能有更多的复选框组,而不是单个表单中的一个.下一组复选框的名称值为name =“field130 [0]”,name =“field130 [1]”和name =“field130 [2]”.我希望你能明白我的观点.
任何帮助将非常感激.
编辑:
if ($('.required:checked').length > 0) { // the "> 0" part is unnecessary,actually [do something] }
请参阅the official jQuery API page for :checked上的第一个示例.
回应你的评论
如果页面上有多个表单,则可以将表单指定为容器:
if ($('#form1_id').find('.required:checked').length) {...
测试多种形式
为每个表单提供类testable_form.
$('.testable_form').each(function() { if ($(this).find('.required:checked').length) { [do something - set a flag,add a class...] } });
以上是大佬教程为你收集整理的jquery – 如何检查在一组具有不同名称值的复选框中是否选中了至少一个复选框全部内容,希望文章能够帮你解决jquery – 如何检查在一组具有不同名称值的复选框中是否选中了至少一个复选框所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。