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

时间:2017-11-26 22:16:01

标签: javascript html validation

我正在尝试通过javascript函数验证HTML表单中的复选框。如果不加以检查,我已经能够让表单返回false,但是当选中该复选框时,我无法提交表单。我做错了什么?

感谢您的时间。

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

}

1 个答案:

答案 0 :(得分:0)

如果稍微更改已检查的逻辑,这将有效。你想比较布尔值而不是字符串“true”

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

编辑:我更改了else块中传递的元素id,以便正确地将#rectangle background设置为白色。