如何通过 JavaScript 动态选中/取消选中 html 复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19666525/
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
How to dynamically check/uncheck html checkbox by JavaScript
提问by Googlebot
I know that several questions about this topic have been asked, but I was unable to find an answer for my case.
我知道有人问过关于这个主题的几个问题,但我无法找到我的案例的答案。
I have a checked checkbox
as
我有一个检查checkbox
为
<input type="checkbox" name="text" checked="checked" />
I need to send ajax request by checking/unchecking, but I do not know what can be the reliable (with browser compatibility) for an if statement
such as
我需要通过选中/取消选中来发送 ajax 请求,但我不知道什么是可靠的(具有浏览器兼容性),if statement
例如
if (this.value == 'on')
{
this.value = 'off';
ajax call;
}
else
{
this.value ='on';
ajax call;
}
Note that the value is not important here, and we need to catch checked/unchecked
, but how control the checked element by JavaScript
when the html original element has checked="checked"
?
注意这里的值并不重要,我们需要catch checked/unchecked
,但是JavaScript
当html原始元素有时如何控制checked元素checked="checked"
呢?
If using checked
instead of value
as
如果使用checked
而不是value
作为
if (this.checked == true)
{
this.checked = false;
ajax call;
}
else
{
this.checked =true;
ajax call;
}
The tick of checkbox
will not be changed in the browser (always ticked).
的蜱checkbox
不会在浏览器中改变(总是选中)。
回答by Hanlet Esca?o
The following should work:
以下应该工作:
function myFunction(elem)
{
if (elem.checked)
{
alert("Im Checked");
}
else
{
alert("Im not checked");
}
}
Markup:
标记:
<input type="checkbox" name="text" checked="checked" onchange="myFunction(this);" />
Update: To change the check from other element:
更新:从其他元素更改检查:
document.getElementById("chk").checked = true;
or
或者
document.getElementById("chk").checked = false;
Example: http://jsfiddle.net/QMhn5/1/
回答by pax162
If you can use jquery, this should work:
如果您可以使用 jquery,这应该可以工作:
<input type="checkbox" id="c1" />
$("#c1").change(function(){
var checked = $(this).is(":checked");
console.log(checked);
//ajax call
})
Fiddle: http://jsfiddle.net/XUgTC/, try clicking the checkbox and look in the console.
小提琴:http: //jsfiddle.net/XUgTC/,尝试单击复选框并查看控制台。