如果仅显示复选框,则复选框验证

时间:2016-08-25 15:04:51

标签: javascript html checkbox

我有一个带有复选框的表单,在某些情况下显示。我想检查复选框是否仅在它显示的情况下被选中,对于其他情况我希望单击提交按钮提交表单。我编写了以下函数,但它不起作用:

function checkTheBox() {
window.onload = function() {
var visible = document.getElementById("checkbox").isDisplayed();
if(!visible)
    return true;
else if(visible){
    var checkbox = document.getElementById("checkbox");
    if(checkbox.checked)
        return true;   }
    else{
        alert('You must agree to the terms first.');
        return false;
    }
}; }

这些是我的html元素:

  <div class='input-block' id='div_checkbox' style='display: none;'> 
  <input type="checkbox" id="checkbox" name="checkbox" value="0">
  <b>I agree to all terms and conditions</b><br />
    </div>
    

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您必须检查该元素是否为undefined

但请注意,用户可以通过控制台删除您的复选框,并且无需选中复选框即可提交表单。

此外,您不必使用window.onload = function() { ... },只需使用此代码并在表单提交时调用函数checkTheBox

function checkTheBox() {
  if (document.getElementById("checkbox") === 'undefined') {
    return true;
  }
  else {
    var checkbox = document.getElementById("checkbox");

    if (checkbox.checked) {
      return true;
    }
    else {
      alert('You must agree to the terms first.');
      return false;
    }
  }
}

但正如@ADyson所说,始终在服务器端验证您的数据。

相关问题