简体   繁体   English

Javascript复选框检查

[英]Javascript checkbox checking

I would like to use Javascript to check if a checkbox has been checked and if the checkbox is not check, the submission form would not continue until it is checked. 我想使用Javascript来检查是否已选中复选框,如果未选中该复选框,则提交表单在检查之前不会继续。 Below are my codes. 以下是我的代码。

<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>

Whenever the form is checked or not, it returns the alert warning that the form have not been checked despite me checking it manually. 无论何时检查表单,它都会返回警告警告,即尽管我手动检查了表单,但仍未检查表单。 How should I fix it ? 我该如何解决?

You have to bind the event to the form instead of the submit button. 您必须将事件绑定到表单而不是提交按钮。 Also, if you want the checkbox input to be submitted, attach a name instead of ID: 此外,如果要提交复选框输入,请附加名称而不是ID:

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

Then, modify the function: 然后,修改功能:

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;
    }
}

You are checking if the submit button is checked, which it naturally never will be. 您正在检查是否已选中提交按钮,这自然不会。

Send the form to the function rather than the submit button itself: 将表单发送到函数而不是提交按钮本身:

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

You need a name on the checkbox to find it: 您需要在复选框上找到一个名称才能找到它:

Use the form reference to access the checkbox: 使用表单引用访问复选框:

<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>

Because you added that function in the onclick of the submit button, value of 'this' is not referring to the checkbox that you expect to receive it in the function. 因为您在提交按钮的onclick中添加了该函数,所以'this'的值不是指您希望在函数中接收它的复选框。 You can replace 'this' by document.getElementById('acknowledgement') 你可以用document.getElementById('acknowledge')替换'this'

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

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