1

I have some check boxes like so:

<input class="mandatory" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes">Option 1<br>
<input class="mandatory" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes">Option 2<br>
<input class="mandatory" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes">Option 3<br>

(yes I know the <input> tags are not closed, maybe I need to fix that!)

And I want to require that the user checks at least one of them. So I have this JavaScript:

jQuery.ready({function() {jQuery.validator.addClassRules('mandatory', {required: true});}});

to add validation to the check boxes. However this doesn't work; from stepping through the code it looks like the validation code is executed but it somehow passes even if all the check boxes are blank. How can I require the user to check at least one box? I was able to do it by giving them all the same name Notes8 but that won't work in this app because other code is relying on them having unique names.

2
  • Is this like a form or something? Can you post the rest of the html and jquery? Commented Jan 27, 2020 at 22:07
  • Yes, this is part of a form. There's a lot of additional code and I'm not sure what in particular is relevant here. Commented Jan 28, 2020 at 19:24

1 Answer 1

2

A common way to arrayify a group of checkboxes (or radio inputs) is to use name=*[].
Assign a rule to the "Notes8[]" prop selector and use minlength: 1 property:

jQuery(function($) { // DOM ready and $ alias in scope

  $("#myForm").validate({
    rules: {
      "Notes8[]": {
        required: true,
        minlength: 1
      }
    },
    messages: {
      "Notes8[]": "Select at least one"
    }
  });

});
<form id="myForm">
  <label>
    <input class="mandatory Notes8_group" name="Notes8[]" type="checkbox" value="n8_1_yes"> Option 1
  </label>
  <label>
    <input class="mandatory Notes8_group" name="Notes8[]" type="checkbox" value="n8_2_yes"> Option 2
  </label>
  <label>
    <input class="mandatory Notes8_group" name="Notes8[]" type="checkbox" value="n8_3_yes"> Option 3
  </label>

  <button type="submit">SEND</button>
</form>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>

Kudos to: https://stackoverflow.com/a/4120320/383904

Custom validator for multiple checkboxes

If you want to build your custom validator this should give you a go:

jQuery(function($) { // DOM ready and $ alias in scope

  function validateMultiple (selector, n, isExactlyN) {
    const totChecked = $(selector).filter(':checked').length;
    return !(isExactlyN ? totChecked == n : totChecked >= n);
  }
  

  $('#myForm').on('submit', function(ev) {
    if (validateMultiple('.Notes8_group', 1)) {
      ev.preventDefault();
      alert("Select at least one"); // Your custom error here
    }
  });

});
<form id="myForm">
  <label>
    <input class="mandatory Notes8_group" name="Notes8~1" type="checkbox" value="n8_1_yes"> Option 1
  </label>
  <label>
    <input class="mandatory Notes8_group" name="Notes8~2" type="checkbox" value="n8_2_yes"> Option 2
  </label>
  <label>
    <input class="mandatory Notes8_group" name="Notes8~3" type="checkbox" value="n8_3_yes"> Option 3
  </label>

  <button type="submit">SEND</button>
</form>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>

you can use the function like:

Example 1: At least one:

validateMultiple('.Notes8_group', 1)

Example 2: Exactly two:

validateMultiple('.Notes8_group', 2, true)

Extra tip: If you cannot (for some reason) assign group classes, you could use the attribute selector []:

validateMultiple('[name^="Notes8~"]', 1)

which will target all by name which starts with "Notes8~", therefore all name= Notes8~1, Notes8~2 and Notes8~3 elements.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the thorough answer! So I tried your second example, with the custom validator, and it seems to be having an issue with the version of jQuery I'm running. This is an old app which is using a variety of versions of jQuery in various places (I know, I know...) and the version in use here is 1.4.4, which doesn't seem to support the "on" method of a form; I get "Uncaught TypeError: $(...).on is not a function". Is there any way to do this that is compatible with jQuery 1.4.4? I'm hesitant to upgrade jQuery because I'm new to this project and I don't want to break anything else...
As for the first example, I can't change the names of the check boxes; that would break.. something else, I forget what, someone told me and I forgot what it was.
@ekolis try using .bind( (instead of .on()
Thanks, that worked! Now all I need to do is hook this into the validator somehow so the validation message can appear on the form itself in red, not just as an alert.
@ekolis you're welcome. The jQuery.validate documentation could help on that matter I hope I've seen yesterday it has some onValidation or onSubmit hooks, otherwise you could also mimick some elements with those .error class to appear... Not sure at this point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.