[英]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.