繁体   English   中英

Javascript复选框检查

[英]Javascript checkbox checking

我想使用Javascript来检查是否已选中复选框,如果未选中该复选框,则提交表单在检查之前不会继续。 以下是我的代码。

<SCRIPT language=javascript>
function checkAcknowledgement(checkbox){
    alert(checkbox.toString());
    if (checkbox.checked == false){
        alert('Please read through the acknowledgement and acknowledge it.');
        return false;
    } else {
        return true;
    }
}
</script>

<form action="ioutput.php" method="POST">
    <input name="form" type="hidden" id="form" value="true">
    ... some html form ...
    <input type="checkbox" id="acknowledgement" value="1" /><br><br>
    <input type="submit" value="submit" onclick="return checkAcknowledgement(this)"/>
</form>

无论何时检查表单,它都会返回警告警告,即尽管我手动检查了表单,但仍未检查表单。 我该如何解决?

您必须将事件绑定到表单而不是提交按钮。 此外,如果要提交复选框输入,请附加名称而不是ID:

<input type="checkbox" name="acknowledgement" value="1" /><br><br>
<form action="ioutput.php" method="POST" onsubmit="return checkAcknowledgement(this)">

然后,修改功能:

function checkAcknowledgement(form){
    var checkbox = form["acknowledgement"];
    alert(checkbox); //shows [HTMLInputElement]
    if (!checkbox.checked){ //A shorter method for checkbox.checked == false
        alert('Please read through the acknowledgement and acknowledge it.');
        return false;
    } else {
        return true;
    }
}

您正在检查是否已选中提交按钮,这自然不会。

将表单发送到函数而不是提交按钮本身:

<input type="submit" value="submit" onclick="return checkAcknowledgement(this.form)"/>

您需要在复选框上找到一个名称才能找到它:

使用表单引用访问复选框:

<script type="text/javascript">

function checkAcknowledgement(frm){
  var checked = frm.acknowledgement.checked;
  if (!checked){
    alert('Please read through the acknowledgement and acknowledge it.');
  }
  return checked;
}

</script>

因为您在提交按钮的onclick中添加了该函数,所以'this'的值不是指您希望在函数中接收它的复选框。 你可以用document.getElementById('acknowledge')替换'this'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM