mercredi 14 février 2018

How to group checkboxes for validation in Bootstrap

I have a simple form which has 2 checkboxes. I want to submit the form if any one of the checkbox is checked. Below code requires to check both of them. I tried grouping checkboxes by using name attribute but thats not sufficient, I am missing something. How can we group checkboxes for validation so that if any one is selected then form should be submited. Any suggestion would be helpful.

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<form class="needs-validation" novalidate>

    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="Check1" name="select" required>
      <label class="form-check-label" for="Check1">Option 1</label>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="Check2" name="select" required>
      <label class="form-check-label" for="Check2">Option 2</label>
    </div>

  <button class="btn btn-primary" type="submit">Submit</button>

</form>

<script>

(function() {
  'use strict';
  window.addEventListener('load', function() {

    var forms = document.getElementsByClassName('needs-validation');

    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>
</body>
</html>




Aucun commentaire:

Enregistrer un commentaire