我的复选框验证有问题吗?

时间:2016-06-04 16:49:05

标签: javascript html forms checkbox

我正在尝试验证包含多个字段的表单。使用当前的js我可以成功验证除复选框之外的每个字段/输入。我想确保提交表单的用户至少检查一个复选框(suites [])。为方便阅读,我删除了其他字段,因此您只能看到复选框。

下面你会找到τhetml表格和js:

< script type = "text/javascript" >
  function validateForm() {
    var name = document.forms["booking"]["name"].value;
    var surname = document.forms["booking"]["surname"].value;
    var city = document.forms["booking"]["city"].value;
    var country = document.forms["booking"]["country"].value;
    var phone = document.forms["booking"]["phone"].value;
    var email = document.forms["booking"]["email"].value;
    var arrival = document.forms["booking"]["arrival"].value;
    var departure = document.forms["booking"]["departure"].value;
    var suites = document.forms["booking"]["suites"].value;
    var persons = document.forms["booking"]["persons"].value;
    var payment = document.forms["booking"]["payment"].value;

    if (name === null || name === "" || surname === null || surname === "" || city === null || city === "" || country === null || country === "" || phone === null || phone === "" || email === null || email === "" || arrival === null || arrival === "" || departure === null || departure === "" || persons === null || persons === "" || payment === null || payment === "" || suites === null || suites === "") {
      alert("PLEASE FILL ALL REQUIRED FIELDS(*)");
      return false;
    }
var elements = document.getElementsByName('suites[]');
  var flag = false;
		for(i = 0; i < elements.length; i++) {
    		if(elements[i].checked == true) {
        	//flag = true;
        		return true;
    		}else{
    			alert("PLEASE SELECT AT LEAST ONE SUITE(*)");
  				return false;
    }
  }
  } < /script>
<form name="booking" method="post" onsubmit="return validateForm()" action="procbook.php">
  <div class="row">
    <div class="col-sm-6 col-xs-12">
      <div class="form-group">
        <label>Suites<span class="required">*</span>
        </label>
        <div class="checkbox">
          <label>
            <input name="suites[]" type="checkbox" value="suite1">suite1
          </label>
          <label>
            <input name="suites[]" type="checkbox" value="suite2">suite2
          </label>
          <label>
            <input name="suites[]" type="checkbox" value="suite3">suite3
          </label>
          <label>
            <input name="suites[]" type="checkbox" value="suite4">suite4
          </label>
          <label>
            <input name="suites[]" type="checkbox" value="suite5">suite5
          </label>
        </div>
      </div>
    </div>
  </div>
</form>

我很感激任何建议,建议,帮助。

感谢。

1 个答案:

答案 0 :(得分:0)

我要做的是遍历复选框输入并查看是否至少有一个已选中。如果是这样,我会将标志设置为true。让我举个例子:

function validateForm() {
    var elements = document.getElementsByName('suites[]');
    var flag = false;
    for(i = 0; i < elements.length; i++) {
        if(elements[i].checked == true) {
            flag = true;
        }
    }
}

然后,您可以使用flag检查其中至少有一个是否为真。