验证多组两个单选按钮

时间:2017-06-15 15:09:23

标签: javascript forms validation radio-button

如何验证多组两个单选按钮,其中一个收音机为真,另一个为假。我使用Javascript但它无法正常工作。我的意思是,如果我从这些组中选择任何一个无线电,它将验证并提交。请参阅下面的代码。

  <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>

我想验证所有真正的选项。如果其中任何一个被错误选择,它应该给出错误。你能帮我吗?

1 个答案:

答案 0 :(得分:1)

在这里,

Vanilla JavaScript解决方案:

<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>

*我重写了HTML代码。