如何通过 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:24:21  来源:igfitidea点击:

How to dynamically check/uncheck html checkbox by JavaScript

javascriptcheckbox

提问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 checkboxas

我有一个检查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 statementsuch 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 JavaScriptwhen the html original element has checked="checked"?

注意这里的值并不重要,我们需要catch checked/unchecked,但是JavaScript当html原始元素有时如何控制checked元素checked="checked"呢?

If using checkedinstead of valueas

如果使用checked而不是value作为

if (this.checked == true)
{
this.checked = false;
ajax call;
}
else
{
this.checked =true;
ajax call;
}

The tick of checkboxwill 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);" />

http://jsfiddle.net/QMhn5/

http://jsfiddle.net/QMhn5/

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/

示例: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/,尝试单击复选框并查看控制台。