繁体   English   中英

jQuery Validation至少选中一个复选框

[英]jQuery Validation at least one checkbox is selected

我有以下用于表单复选框的html代码

<div class="drinking col-xs-12">
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="allwines" id="allwines" value="0" class="require-one col-xs-1 styled myClassA"  value="0" data-label="All Wines" />
    <input id='allwinesHidden'  type='hidden' value='0' name='allwines'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="beer" id="beer" value="0" class="require-one col-xs-1 styled myClassB"  value="0"  data-label="Beer" />
    <input id='beerHidden'  type='hidden' value='0' name='beer'>
  </div>
  <div class="clearix"></div>
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="redwines" id="redwines" value="0" class="require-one col-xs-1 styled myClassC"  value="0" data-label="Red Wines" />
    <input id='redwinesHidden'  type='hidden' value='0' name='redwines'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="cider" id="cider" value="0" class="require-one col-xs-1 styled myClassD"  value="0" data-label="Cider" />
    <input id='ciderHidden'  type='hidden' value='0' name='cider'>
  </div>
  <div class="clearix"></div>
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="whitewines" id="whitewines" value="0" class="require-one col-xs-1 styled myClassE"  value="0" data-label="White Wines" />
    <input id='whitewinesHidden'  type='hidden' value='0' name='whitewines'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="spirits" id="spirits" value="0" class="require-one col-xs-1 styled myClassF"  value="0" data-label="Spirits" />
    <input id='spiritsHidden'  type='hidden' value='0' name='spirits'>
  </div>
  <div class="clearix"></div>
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="sparkling" id="sparkling" value="0" class="require-one col-xs-1 styled myClassG"  value="0" data-label="Sparkling/Champagne" />
    <input id='sparklingHidden'  type='hidden' value='0' name='sparkling'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="fortified" id="fortified" value="0" class="require-one col-xs-1 styled myClassH"  value="0" data-label="Fortified" />
    <input id='fortifiedHidden'  type='hidden' value='0' name='fortified'>
  </div>
  <div id="error_msg3"></div>
  <div class="clearix"></div>
</div>
</div>

我要确保至少选中了一个复选框。

我希望不要把它当作一个警告框; 但是该消息需要显示在div error-msg3中。

请注意,所有输入都具有不同的类名称和ID。 临时链接位于

https://bitly.com/1i3f1MY

我正在使用jQuery验证来验证表单的其余部分。 通过jquery验证来获取解决方案将是很好的。

提前致谢

这很简单……

function validate_form()
{
valid = true;

if($('input[type=checkbox]:checked').length == 0)
{
    alert ( "ERROR! Please select at least one checkbox" );
    valid = false;
}

return valid;
}

的HTML

<form name="myform" method="post" action="#" onsubmit="return validate_form();">
<input type="checkbox" name="box1"  value="box1">Box1
<input type="checkbox" name="box2"  value="box2">Box2
<input name="submit" type="submit" value="Submit"/>
</form>

您将必须更改复选框的名称属性,并为其添加minlength设置为1的规则。

之后,您可以显示自定义消息,并使用以下命令将其附加到#error_msg3

if(element.attr("name") == "check") error.appendTo("#error_msg3")

编辑

$("input[type='checkbox'][name='check']").change(function() {
    if ($("input[type='checkbox'][name='check']:checked").length){
        $(this).valid()
    }
})

编辑2

我更新了小提琴,现在无论您是否至少选中一个复选框,消息都可以正确切换。

$("input[type='checkbox'][name='check']").change(function() {
    $('#submitDetails').valid();
});


在这里摆弄

引用OP

“我要确保至少选中了一个复选框。”

如果您想使用jQuery Validate插件, 并且所有复选框都使用不同的name ,则只需使用require_from_group方法,该方法是require_from_group additional-methods.js文件的一部分。

由于您已经在这些复选框上建立了require-one名为require-one的通用类,因此更加容易。

$('#form').validate({
    rules: {
        fieldname: {
            require_from_group: [1, '.require-one']
        },
        // declare same rule on all eight checkboxes
        ....
        ....
    }
});

然而,而不是内声明的这些所有八个.validate()您可以使用.rules('add')方法的jQuery内.each()在一次声明它们。

$('.require-one').each(function () {
    $(this).rules('add', {
        require_from_group: [1, this],
        messages: {
            require_from_group: "please check one"
        }
    });
});

然后要将所有八条消息合并为一个,请使用groups选项...

$('#form').validate({
    groups: {  // combine these error messages into one
        checkboxes: 'allwines beer redwines cider whitewines spirits sparkling fortified'
    }
});

工作演示: http//jsfiddle.net/JVWu2/1/

将错误消息放入#error_msg3错误框与放置任何其他jQuery Validate消息没有什么不同。

试试这个

$("#YourbuttonId").click(function(){
    if($('input[type=checkbox]:checked').length == 0)
    {
        alert('Please select atleast one checkbox');
    }
});

通过插件

的HTML

<label class="checkbox inline">
<input type="checkbox" id="typecb1" name="spamm[]" value="Loading Point"> Loading Point
</label>
<label class="checkbox inline">
<input type="checkbox" id="typecb2" name="spamm[]" value="Unloading Point"> Unloading Point
</label>
<label class="checkbox">
<input type="checkbox" id="typecb3" name="spamm[]" value="Retailer Unloading"> Retailer Unloading
</label>

脚本

rules:{
     "spamm[]": { 
      required: true, 
      minlength: 1 
      }
   }

尝试

添加此代码即可

var chck = $('input[type=checkbox]');
chck.addClass('check-one');
$.validator.addMethod('check-one', function (value) {
    return (chck.filter(':checked').length > 0);
}, 'Check at least one checkbox');


小提琴演示

组仅在前面的第一个复选框中显示错误

 var chck = $('input[type=checkbox]'); chck.addClass('check-one'); $.validator.addMethod('check-one', function (value) { return (chck.filter(':checked').length > 0); }, 'Check at least one checkbox'); var chk_names = $.map(chck, function (el, i) { return $(el).prop("name"); }).join(" "); $("#submitDetails").validate({ groups: { checks: chk_names }, submitHandler: function (form) { alert('Form Submited'); return false; } }); 


如果您希望错误显示在所有复选框的前面,请删除组

小提琴演示

 $("#submitDetails").validate({ submitHandler: function (form) { alert('Form Submited'); return false; } }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM