Javascript 更改/获取 CheckBox 的检查状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5539139/
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-08-23 17:43:28  来源:igfitidea点击:

Change/Get check state of CheckBox

javascripthtml

提问by Stan

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.

我只想用 JavaScript 获取/更改 CheckBox 的值。并不是说我不能为此使用 jQuery。我试过这样的事情,但它不起作用。

JavaScript function

JavaScript 函数

    function checkAddress()
    {
        if (checkAddress.checked == true)
        {
            alert("a");
        }
    }

HTML

HTML

<input type="checkbox" name="checkAddress" onchange="checkAddress()" />

回答by Tim Down

Using onclickinstead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.

使用onclick反而会工作。从理论上讲,它可能无法捕获通过键盘所做的更改,但所有浏览器在通过键盘检查时似乎都会触发该事件。

You also need to pass the checkbox into the function:

您还需要将复选框传递给函数:

function checkAddress(checkbox)
{
    if (checkbox.checked)
    {
        alert("a");
    }
}

HTML

HTML

<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />

回答by Kevin

You need to retrieve the checkbox before using it.

您需要在使用它之前检索该复选框。

Give the checkbox an idattribute to retrieve it with document.getElementById(..)and then check its current state.

给复选框一个id属性来检索它,document.getElementById(..)然后检查它的当前状态。

For example:

例如:

function checkAddress()
{
    var chkBox = document.getElementById('checkAddress');
    if (chkBox.checked)
    {
        // ..
    }
}

And your HTML would then look like this:

然后您的 HTML 将如下所示:

<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>

(Also changed the onchangeto onclick. Doesn't work quite well in IE:).

(也更改onchangeonclick在 IE 中效果不佳:)。

回答by Pedro Sousa

I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.

我知道这是一个很晚的回复,但是这段代码更加灵活,应该可以帮助像我这样的后来者。

function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.

    if(document.getElementById(from).checked==true) 
    //checks status of "from" element. change to whatever validation you prefer.
        {
            document.getElementById(to).checked=true;
             //if validation returns true, checks target checkbox
        }
    else
        {   
            document.getElementById(to).checked=false; 
             //if validation returns true, unchecks target checkbox
        }
}

HTML being something like

HTML就像

<input type="radio" name="bob" onclick="copycheck('from','to');" />

where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to". As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.

其中“from”和“to”是您希望复制“to”的元素“from”的各自ID。照原样,它可以在复选框之间工作,但您可以输入您希望的任何 ID 和您希望的任何条件,只要在从 html 事件调用发送变量时正确定义了“to”(即要操作的复选框)。

Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.

请注意,正如 SpYk3HH 所说,默认情况下您要使用的目标是一个数组。使用 Web 开发人员工具栏中的“显示元素信息”工具将帮助您找到相应复选框的完整 ID。

Hope this helps.

希望这可以帮助。

回答by SpYk3HH

I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

我知道这是迟到的信息,但在 jQuery 中,使用 .checked 是可能且简单的!如果你的元素是这样的:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

您可以轻松地获取/设置检查状态,如下所示:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

秘诀是使用“[0]”数组索引标识符,它是 jquery 对象的元素!请享用!

回答by Shadow Wizard is Ear For You

Needs to be:

需要是:

if (document.forms[0].elements["checkAddress"].checked == true)

Assuming you have one form, otherwise use the form name.

假设您有一个表单,否则使用表单名称。

As a side note, don't call the element and the function in the same name it can cause weird conflicts.

作为旁注,不要以相同的名称调用元素和函数,这可能会导致奇怪的冲突。

回答by Aarón

You need this:

你需要这个:

window.onload = function(){
    var elCheckBox=document.getElementById("cbxTodos");
    elCheckBox.onchange =function (){
        alert("como ves");
    }
};

回答by itzmukeshy7

<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />

回答by Ramya Prakash Rout

var val = $("#checkboxId").is(":checked");

var val = $("#checkboxId").is(":checked");

回答by Sinan Eldem

Here is a quick implementation with samples:

这是一个带有示例的快速实现:

Checkbox to check all items:

复选框以检查所有项目:

<input id="btnSelectAll" type="checkbox">

Single item (for table row):

单个项目(用于表格行):

<input class="single-item" name="item[]" type="checkbox">

Js code for jQuery:

jQuery 的 JS 代码:

$(document).on('click', '#btnSelectAll', function(state) {
    if ($('#btnSelectAll').is(':checked')) {
        $('.single-item').prop('checked', true);
        $('.batch-erase').addClass('d-block');
    } else {
        $('.single-item').prop('checked', false);
        $('.batch-erase').removeClass('d-block');
    }
});

Batch delete item:

批量删除项目:

<div class="batch-erase d-none">
    <a href="/path/to/delete" class="btn btn-danger btn-sm">
        <i class="fe-trash"></i> Delete All
    </a>
</div>

回答by daryosh setorg

This will be useful

这将是有用的

$("input[type=checkbox]").change((e)=>{ 
  console.log(e.target.checked);
});