Javascript one函数验证相同的表单复选框组和单选按钮组

时间:2017-09-21 13:18:58

标签: javascript html function

我是Javascript初学者,编写JS函数来验证单选按钮组和复选框组;如果其中任何一个未被完全取消选中,则相应的警报会显示并停止表单提交。

我复制了单选按钮组验证的代码,然后通过添加第二个“拆分器”功能进行调整,该功能将无线电和复选框名称作为2个参数,然后将这两个名称依次发送到“验证”功能。

这样可行,但是在一个函数,精选案例的JS版本或其他东西中有更简洁的方法吗?

  <script>

  function splitter(mainst, Cst) {
  validate(mainst);
  validate(Cst);
  }

//'unchecked' counts number of unchecked boxes or buttons
//then compares this to total number in the group, and if same
//this means nothing is checked, therefore show alert and return false.
      function validate(grpname) {
      var unchecked = 0, selectgroup=document.getElementsByName(grpname)
      for(i=0;i<selectgroup.length;i++) {
      if(selectgroup.item(i).checked == false) {
      unchecked++;
      }
      }
      if(unchecked == selectgroup.length) {
        if (grpname == 'mainstreet') {
        alert("Please select a main street");
        return false;
        }
        else {
        alert("Please select your C street(s)");
        return false;
        }
      } else {
      return true;
      }
      }

      </script>

此处的示例表单:

  <form action="" method="post" onsubmit="return splitter('mainstreet', 'Cstreet')">
  Street:
  <input type="radio" name="mainstreet" value="jones"> jones street
  <input type="radio" name="mainstreet" value="bones"> bones street
  <input type="radio" name="mainstreet" value="drones"> drones street
  <input type="radio" name="mainstreet" value="foobar"> foobar street
  <br /><br />
  Side street:
  <input type="checkbox" name="Cstreet" value="barfoo"> barfoo street
  <input type="checkbox" name="Cstreet" value="candoo"> candoo street
  <input type="checkbox" name="Cstreet" value="cantdo"> cantdo street
  <input type="checkbox" name="Cstreet" value="canoe"> canoe street
  <input type="checkbox" name="Cstreet" value="wahoo"> wahoo street

  <input type="submit" value="Submit" />
  </form>

1 个答案:

答案 0 :(得分:0)

<script>
function splitter(mainst, Cst) {
    if(document.querySelector('input[name="'+mainst+'"]:checked') == null ){
        alert("Please select a main street");
        return false;
    }
    else if (document.querySelector('input[name="'+Cst+'"]:checked') == null) {
        alert("Please select your C street(s)");
        return false;
    }
 }
</script>