我想使用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>
无论何时检查表单,它都会返回警告警告,即尽管我手动检查了表单,但仍未检查表单。我该如何解决?
答案 0 :(得分:12)
您必须将事件绑定到表单而不是提交按钮。此外,如果要提交复选框输入,请附加名称而不是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;
}
}
答案 1 :(得分:1)
您正在检查是否已选中提交按钮,这当然不会。
将表单发送到函数而不是提交按钮本身:
<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>
答案 2 :(得分:1)
因为您在提交按钮的onclick中添加了该功能,所以'this'的值不是指您希望在函数中接收它的复选框。您可以通过document.getElementById('acknowledgement')
替换'this'