Javascript 使用javascript获取复选框状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6204885/
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
Get checkbox status using javascript
提问by Sasindu H
This is my checkbox HTML code
这是我的复选框 HTML 代码
<input id="termsCheckbox" name="termsCheckbox" type="checkbox" value="terms" <?PHP echo $terms; ?> class="checkbox">
this is javascript code
这是javascript代码
var terms = $("#termsCheckbox");
function validateTerms(){
if(termsCheckbox.checked == false){
terms_div.addClass("terms_error");
return false;
}
else{
terms_div.removeClass("terms_error");
return true;
}
}
I want to check whether checkbox checked or not and if not add a class to terms_div. Please help me to solve this problem. thanks
我想检查复选框是否被选中,如果没有向terms_div 添加一个类。请帮我解决这个问题。谢谢
回答by Rudu
You need to access the className
variable (pure JS) the following assumes your div
has an ID of terms_div
, that terms_error
is the only class you might want on the div
, and that you setup your checkbox with onClick="validateTerms();"
您需要访问className
变量(纯 JS),以下假设您div
的 ID 为terms_div
,这terms_error
是您可能想要的唯一类div
,并且您设置了复选框onClick="validateTerms();"
function validateTerms(){
var c=document.getElementById('termsCheckbox');
var d=document.getElementById('terms_div');
if (c.checked) {
d.className='';
return true;
} else {
d.className='terms_error';
return false;
}
}
回答by karim79
Simply bind an onchange handler to your checkbox.
只需将 onchange 处理程序绑定到您的复选框。
$("#termsCheckbox").change(function() {
// class will be removed if checked="checked"
// otherwise will be added
$(this).toggleClass("terms_error", !this.checked);
}).change(); // set initial state
回答by Loktar
Live Demo(Click the "Terms Div" text to test)
现场演示(点击“Terms Div”文本进行测试)
I didnt see the question tagged with jQuery, but I noticed a jQery selector was used.. so just to be safe I did it with pure JS anyway.
我没有看到用 jQuery 标记的问题,但我注意到使用了 jQery 选择器..所以为了安全起见,我还是用纯 JS 做的。
Pure JS
纯JS
var terms = document.getElementById("termsCheckbox"),
terms_div = document.getElementById("terms_div");
function validateTerms(){
if(terms.checked == false){
if(terms_div.className.indexOf("terms_error")<0){
terms_div.className += " terms_error";
}
return false;
}else{
terms_div.className = terms_div.className.replace(/\bterms_error\b/,'');
return true;
}
}
回答by cusimar9
try adding onclick="validateTerms();"
on the checkbox tag
尝试添加onclick="validateTerms();"
复选框标签
回答by zod
if(document.form.termsCheckbox.checked==true)
alert('check box is cheked')