ffuentes
ffuentes

Reputation: 1182

Validate required checkbox when one element is marked

What can be done when you have a Bootstrap checkbox group and you need to ask the user to mark at least one box but not all of them?

Bootstrap validation (and browsers) uses the "required" attribute to detect them but it's apparently not made for this use case when many checkboxes are related to one another in a group.

So I wanted to use JavaScript to toggle the attribute on the other ones but I haven't succeeded so far.

<div class="checkbox-group">
  <div class="form-check form-checkbox">
    <input type="checkbox" class="form-check-input" id="choice-64" value="64" name="choice-19" required>
    <label class="form-check-label" for="choice-64"> Manzana</label>
  </div>

  <div class="form-check form-checkbox">
    <input type="checkbox" class="form-check-input" id="choice-65" value="65" name="choice-19" required>
    <label class="form-check-label" for="choice-65"> Sandía</label>
  </div>

  <div class="form-check form-checkbox">
    <input type="checkbox" class="form-check-input" id="choice-66" value="66" name="choice-19" required>
    <label class="form-check-label" for="choice-66"> Melón</label>
  </div>
</div>

I found this code on GitHub but it didn't work well:

$('#myForm .checkbox-group').on('change', 'input[type="checkbox"]', function (e) {
  var $group = $(this)
  var $checkbox = $(e.target)
  $group.not($checkbox).attr('required', !$checkbox.attr('checked'))
})

Upvotes: 0

Views: 826

Answers (1)

Tschitsch
Tschitsch

Reputation: 1338

The following code will change required value on all checkboxes within the group, not only the one changed. In case there is at least one checkbox checked it will set all to false otherwise true.

$('#myForm .checkbox-group').on('change', 'input[type="checkbox"]', function (e) {
  var $checkbox = $(this)
  var $group = $checkbox.parents('.checkbox-group')
  var checkedItems = $('input[type="checkbox"]:checked').length
  $('input[type=checkbox]', $group).attr('required', checkedItems === 0)
})

It makes its easier to handle if you toggle all of them instead of skipping the changed one. try it here: https://jsfiddle.net/buqrn7mt/

Upvotes: 1

Related Questions