0

Currently, I'm using jQuery validation plugin which activates with a simple required keyword inside the input field. But when I'm going to use this in a dynamically created checkbox field, it simply asked to check all checkboxes. But I want at least one checkbox needs to be checked.

 {% for opt in obj.option_array_a %}
      <label>
       <input class="optcheckbox" name="optcheckbox_{{ obj.question_number }}"
           id="{{ obj.id }}__{{ forloop.counter0 }}" type="checkbox"
        value="{{ opt }}"/> <span>{{ opt }}</span><br>
        </label>
   {% endfor %}
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Search: https://stackoverflow.com/search?q=%5Bjquery-validate%5D+one+checkbox – Sparky Apr 15 '20 at 15:30
  • **Show us your actual rendered code**. That's likely because all of your checkboxes have a different name. Give them all the same name and the required rule will only make sure at least one is checked. See: http://jsfiddle.net/7kdx4t6u/1/ – Sparky Apr 15 '20 at 20:42

1 Answers1

-1

Here is an example of how you can check if at least one checkbox is checked.

$( document ).ready(function() {
  $('input[name="question_1"]').change(function(){
    $('#result').text($('input[name="question_1"]:checked').length > 0 ? "OK" : "KO");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="question_1" value="answer 1" /> Answer 1
<input type="checkbox" name="question_1" value="answer 2" /> Answer 2
<div id="result"></div>
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41