Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - validation at least one checkbox (multiple group of checkboxes)

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 ~

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...