validation at least one checkbox (multiple group of checkboxes)

▼魔方 西西 提交于 2021-02-05 06:53:45

问题


I know this've been answered in here
But my html looks like below :

<div >
    <label> <input type="checkbox" name="service_area[]" value="colorado">colorado</label>
    <label> <input type="checkbox" name="service_area[]" value="michigan">michigan</label>
</div>

<div >
    <label> <input type="checkbox" name="fav[]" value="skiing">skiing</label>
    <label> <input type="checkbox" name="fav[]" value="volley">volley</label>
</div>

Objectives :

  • name must have array, in here : service_area[]
  • must show only one error message

How to achieve this ?
Each time I use jvalidate with '[]' name, it seems that it only reflects to the first element, not all elements.

UPDATE:

I forget to mention that I have more than one group of checkboxes that needed to be checked.
Updated above html.
So, rynhe answer inspired me a bit :

$.validator.addMethod(
  "atleastone",
  function(value, element, params) {
    return $('[name="' + element.name +'"]:checked').size() > 0;
  },
  'at least one');

  rules: {
    'service_area[]': {
      atleastone : true,
    },
    'fav[]': {
      atleastone : true,
    },        

The most important part is 'service_area[]'. Above code works fine for me. Thx ~


回答1:


You do not need to add any special methods in this case. When every checkbox in one group shares the same name, simply use the required rule. Since the names contain brackets, [], enclose it with quotes.

$(document).ready(function () {

    $('#myform').validate({
        rules: {
            'service_area[]': {
                required: true
            },
            'fav[]': {
                required: true
            }
        }
    });

});
  • At least one checkbox from service_area[] group is required.

  • At least one checkbox from fav[] group is required.

I used the errorPlacement option to move the error message before each grouping but you can adjust as needed. See all plugin options.

Working DEMO: http://jsfiddle.net/AsuyC/




回答2:


As per Tats_innit answer which is in validation for at least one checkbox

you can change this line

var checkboxes = $('.require-one');

to

var checkboxes = $('input[name="river[]"]');

as per your html element var checkboxes = $('input[name="service_area[]"');

Live Demo



来源:https://stackoverflow.com/questions/20537440/validation-at-least-one-checkbox-multiple-group-of-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!