2

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 ~

Community
  • 1
  • 1
Hendry H.
  • 1,482
  • 3
  • 13
  • 27

2 Answers2

0

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

Community
  • 1
  • 1
rynhe
  • 2,509
  • 1
  • 21
  • 27
  • forgot your closing square brackets, $('input[name="service_area[]"**]**'); . [attribute-equals-selector](http://api.jquery.com/attribute-equals-selector/) – Mark S Dec 12 '13 at 07:54
  • updated my question. my question should be how to apply this when I have more than one group checkboxes need to be checked. thx anyway. your answer inspired me – Hendry H. Dec 12 '13 at 09:43
0

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/

Sparky
  • 98,165
  • 25
  • 199
  • 285