Ahtsham Ul Haq
Ahtsham Ul Haq

Reputation: 51

Validating multiple groups of two radio buttons

How to validate multiple groups of two radio buttons in which, one radio is true and the other one is false. I am using Javascript but it does not work properly. I mean if I select any one radio from these group it validates and submits it. See the code below.

  <form name="form1" action="http://example.com/" onsubmit="return 
    validateForm()" method="post">
    <div class="btn-group" data-toggle="buttons">
      <label id="yes" class="btn btn-success">
        <input id="true" name="options" type="radio" /> Yes
      </label>
      <label id="no" class="btn btn-success">
        <input id="false" name="options" required="" type="radio" /> No
      </label>
    </div>
    <div class="btn-group" data-toggle="buttons">
      <label id="yes1" class="btn btn-success">
        <input id="true" name="options" type="radio" /> Yes
      </label>
      <label id="no1" class="btn btn-success">
        <input id="false" name="options" required="" type="radio" /> No
      </label>
    </div>
  </form>
  <script>
  function validateForm() {
    var radios = document.getElementsById("true");
    if (radios.checked = true) {
      return true;
    } else {
      alert("error");
    }
  }
  </script>

I would like to validate all true options. And if any one of them is false selected, it should give an error. Can you please help me?

Upvotes: 1

Views: 830

Answers (1)

Alexandr Kazakov
Alexandr Kazakov

Reputation: 698

Here you are,

Vanilla JavaScript solution:

<form id="form_1" name="form" action="#" method="POST">
  <div class="btn-group" data-toggle="buttons">
    <input class="radio_btn" type="radio" name="group1" value="true">Yes
    <input class="radio_btn" type="radio" name="group1" value="false">No
  </div>
  <div class="btn-group" data-toggle="buttons">
    <input class="radio_btn" type="radio" name="group2" value="true">Yes
    <input class="radio_btn" type="radio" name="group2" value="false">No
  </div>
  <button type="submit">Submit</button>
</form>

<script>
  var form = document.querySelector('#form_1');
  var radioList = form.querySelectorAll('.radio_btn');

  form.addEventListener('submit', function() {
    for (var i = 0, length1 = radioList.length; i < length1; i++) {
      if (radioList[i].getAttribute('value') == 'false' && radioList[i].checked) {
        alert("error");
        return false;
      }
    }
  });
</script>

*I rewrite the HTML code.

Upvotes: 1

Related Questions