简体   繁体   English

使用javascript函数验证HTML表单复选框

[英]Validate HTML form checkbox with javascript function

I am trying to validate a checkbox in a HTML form through a javascript function. 我正在尝试通过javascript函数验证HTML表单中的复选框。 I have been able to get the form to return false if left unchecked, but I cannot get the form to submit when the box is checked. 如果不勾选,我已经能够获得返回false的表单,但是当复选框被选中时,我无法提交表单。 What am I doing wrong? 我究竟做错了什么?

Thank you for your time. 感谢您的时间。

<form method="get" action="http://www.randyconnolly.com/tests/process.php" id="mainForm" onsubmit="return Validate()">

<div id="rectangle"> 
           <label>I accept the software license</label>
           <input id="accept" type="checkbox" name="accept" class="required">
        </div>

function Validate() {
//Form Validate
var t = document.getElementById("title").value;
if (t == "") {
    alert("Empty Title Field");
    document.getElementById("title").style.backgroundColor = "red";
}else{
    document.getElementById("title").style.backgroundColor = "white";
}

var d = document.getElementById("description").value;
if (d == "") {
    alert("Empty description field");
    document.getElementById("description").style.backgroundColor = "red";
}else{
    document.getElementById("description").style.backgroundColor = "white";
}

var c = document.getElementById("accept");
if (c.checked != "true") {
    alert("Please accept license");
    document.getElementById("rectangle").style.backgroundColor = "red";
    return false;
}else{
    document.getElementById("accept").style.backgroundColor = "white";
}

} }

This will work if you change your checked logic slightly. 如果您稍微更改检查的逻辑,这将起作用。 You'll want to compare against boolean true instead of string "true" 您将要与布尔值true而不是字符串“ true”进行比较

if (c.checked != true) {
    alert("Please accept license");
    document.getElementById("rectangle").style.backgroundColor = "red";
    return false;
}else{
    document.getElementById("rectangle").style.backgroundColor = "white";
}

edit: I changed the element id passed in the else block so that it would correctly set #rectangle background to white. 编辑:我更改了在else块中传递的元素ID,以便它将#rectangle背景正确设置为白色。

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

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