使用 JavaScript 获取复选框状态
这是我的复选框 HTML 代码,
<input id="termsCheckbox" name="termsCheckbox" type="checkbox" value="terms" <?PHP echo $terms; ?> class="checkbox">
这是 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;
}
}
我想检查复选框是否选中,如果没有,则向 terms_div 添加一个类。请帮我解决这个问题。谢谢
This is my checkbox HTML code
<input id="termsCheckbox" name="termsCheckbox" type="checkbox" value="terms" <?PHP echo $terms; ?> class="checkbox">
this is javascript code
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要访问
className
变量(纯 JS),以下假设您的div
的 ID 为terms_div
,即terms_error 是您在
div
上可能需要的唯一类,并且您可以使用onClick="validateTerms();"
设置复选框You need to access the
className
variable (pure JS) the following assumes yourdiv
has an ID ofterms_div
, thatterms_error
is the only class you might want on thediv
, and that you setup your checkbox withonClick="validateTerms();"
只需将 onchange 处理程序绑定到您的复选框即可。
Simply bind an onchange handler to your checkbox.
尝试在复选框标记上添加
onclick="validateTerms();"
try adding
onclick="validateTerms();"
on the checkbox tag现场演示(点击“Terms Div”文本进行测试)
我没有看到用 jQuery 标记的问题,但我注意到使用了 jQery 选择器..所以为了安全起见,我还是用纯 JS 做了它。
纯JS
Live Demo (Click the "Terms Div" text to test)
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.
Pure JS