javascript 选中时复选框值不会从 false 变为 true
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15939415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checkbox value not changing from false to true when checked
提问by Make a Difference
This javascript function finds the errors in a form and lists them. If there are errors, it creates an error override checkbox to allow submission even with errors. At present the code does not recognize when the checkbox is checked. Apparently the first if statement is always found to be true. Ideas?
这个 javascript 函数在表单中查找错误并列出它们。如果有错误,它会创建一个错误覆盖复选框,即使有错误也允许提交。目前,代码无法识别何时选中复选框。显然,第一个 if 语句总是被发现为真。想法?
function check1()
{
// c_ierrors is the id of the input tag inserted below within the c_erros div
if( document.getElementById("c_ierrors")==null || document.getElementById("c_ierrors").checked!="true" )
{
//if javascript generated form error overide checkbox does not exist or exists but is not true then list errors and don't submit the form
//code to generate divs listing errors
//
if(error=="")
{
//submit form
return true;
}
else
{
error += "<div id=\"c_erow\"><input type=\"checkbox\" id=\"c_ierrors\" name=\"override\" value=\"y\" >Override Errors</div>" //add checkbox to submit form despite errors
document.getElementById("c_errors").innerHTML=error;
alert (document.forms["cform"]["override"].checked);
return false; //stay on page don't submit form
}
}
else
{
//if override checkbox (exists) and is true
return true;
}
}
采纳答案by richard
The problem is in the second part of the first if statement where you compare
问题出在您比较的第一个 if 语句的第二部分
document.getElementById("c_ierrors").checked!="true"
Comparing a boolean to a string gives you the wrong result. You can check this in your JavaScript console with,
将布尔值与字符串进行比较会得到错误的结果。你可以在你的 JavaScript 控制台中检查这个,
bool_val = true
bool_val == "true" # returns false
You either need to compare to true
or just use it as a boolean value. E.g.
您要么需要进行比较,true
要么仅将其用作布尔值。例如
document.getElementById("c_ierrors").checked != true
or
或者
!document.getElementById("c_ierrors").checked
回答by SomeShinyObject
For finding if it's checked, you don't need to evaluate if it is true or not, especially with a String value.
为了查找它是否被选中,您不需要评估它是否为真,尤其是对于 String 值。
You just need to find if it is .checked
你只需要找到它是否是 .checked
If you want to find if it's not .checked
just use:
如果你想找到它是否.checked
不仅仅是使用:
!document.getElementById("c_ierrors").checked
Full code:
完整代码:
document.getElementById("c_ierrors")==null||document.getElementById("c_ierrors").checked
That will work just fine
那会很好用