用jQuery设置复选框的“勾选”?

[英]Setting “checked” for a checkbox with jQuery?


I'd like to do something like this to tick a checkbox using jQuery:

我想用jQuery来勾选一个复选框:

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

Does such a thing exist?

这样的东西存在吗?

38 个解决方案

#1


5272  

jQuery 1.6+

Use the new .prop() method:

使用new .prop()方法:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

jQuery 1.5.x and below

The .prop() method is not available, so you need to use .attr().

.prop()方法不可用,所以您需要使用.attr()。

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using

注意,这是jQuery在1.6版本之前的单元测试所使用的方法,并且更适合使用。

$('.myCheckbox').removeAttr('checked');

since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it - a subtle but probably unwelcome behaviour change.

因为后者将会,如果这个盒子最初被检查过,就会改变对任何包含它的任何形式的调用的行为,这是一个微妙但可能不受欢迎的行为改变。

For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

对于更多的上下文,一些不完整的讨论,讨论了从1.5转换到检查属性/属性的处理。在1.6版本注释和.prop()文档的属性与属性部分中可以找到x到1.6。

Any version of jQuery

If you're working with just one element, you can always just modify the HTMLInputElement's .checked property:

如果只使用一个元素,那么可以只修改HTMLInputElement的.checked属性:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

使用.prop()和.attr()方法的好处是,它们将对所有匹配的元素进行操作。

#2


608  

Use:

使用:

$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);

And if you want to check if a checkbox is checked or not:

如果你想检查复选框是否被选中:

$('.myCheckbox').is(':checked');

#3


281  

This is the correct way of checking and unchecking checkboxes with jQuery, as it is cross-platform standard, and will allow form reposts.

这是用jQuery检查和取消复选框的正确方法,因为它是跨平台的标准,并且允许表单重新发布。

$('.myCheckBox').each(function(){ this.checked = true; });

$('.myCheckBox').each(function(){ this.checked = false; });

By doing this, you are using JavaScript standards for checking and unchecking checkboxes, so any browser that properly implements the "checked" property of the checkbox element will run this code flawlessly. This should be all major browsers, but I am unable to test previous to Internet Explorer 9.

通过这样做,您将使用JavaScript标准来检查和取消检查复选框,因此任何正确实现复选框元素的“选中”属性的浏览器都将完美地运行此代码。这应该是所有主要的浏览器,但是我不能测试之前的ie9。

The Problem (jQuery 1.6):

问题(jQuery 1.6):

Once a user clicks on a checkbox, that checkbox stops responding to the "checked" attribute changes.

一旦用户点击了复选框,复选框就会停止对“勾选”属性更改的响应。

Here is an example of the checkbox attribute failing to do the job after someone has clicked the checkbox (this happens in Chrome).

这里有一个复选框属性的例子,当有人点击了复选框(这在Chrome中发生)之后,就无法完成任务。

Fiddle

小提琴

The Solution:

解决方案:

By using JavaScript's "checked" property on the DOM elements, we are able to solve the problem directly, instead of trying to manipulate the DOM into doing what we want it to do.

通过在DOM元素上使用JavaScript的“检查”属性,我们能够直接解决问题,而不是试图操纵DOM来做我们想要做的事情。

Fiddle

小提琴

This plugin will alter the checked property of any elements selected by jQuery, and successfully check and uncheck checkboxes under all circumstances. So, while this may seem like an over-bearing solution, it will make your site's user experience better, and help prevent user frustration.

这个插件将改变jQuery选择的任何元素的检查属性,并在所有情况下成功地检查和取消复选框。因此,虽然这看起来像是一个过度的解决方案,它将使您的站点的用户体验更好,并有助于防止用户的沮丧。

(function( $ ) {
    $.fn.checked = function(value) {
        if(value === true || value === false) {
            // Set the value of the checkbox
            $(this).each(function(){ this.checked = value; });
        } 
        else if(value === undefined || value === 'toggle') {
            // Toggle the checkbox
            $(this).each(function(){ this.checked = !this.checked; });
        }

        return this;
    };
})( jQuery );

Alternatively, if you do not want to use a plugin, you can use the following code snippets:

或者,如果您不想使用插件,您可以使用以下代码片段:

// Check
$(':checkbox').prop('checked', true);

// Un-check
$(':checkbox').prop('checked', false);

// Toggle
$(':checkbox').prop('checked', function (i, value) {
    return !value;
});

#4


128  

You can do

你可以做

$('.myCheckbox').attr('checked',true) //Standards compliant

or

$("form #mycheckbox").attr('checked', true)

If you have custom code in the onclick event for the checkbox that you want to fire, use this one instead:

如果您想要使用的复选框的onclick事件中有自定义代码,请使用以下命令:

$("#mycheckbox").click();

You can uncheck by removing the attribute entirely:

您可以通过完全删除属性来取消检查:

$('.myCheckbox').removeAttr('checked')

You can check all checkboxes like this:

你可以这样检查所有的复选框:

$(".myCheckbox").each(function(){
    $("#mycheckbox").click()
});

#5


66  

You can also extend the $.fn object with new methods:

您还可以扩展$。fn对象的新方法:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

Then you can just do:

然后你可以这样做:

$(":checkbox").check();
$(":checkbox").uncheck();

Or you may want to give them more unique names like mycheck() and myuncheck() in case you use some other library that uses those names.

或者,您可能希望给它们提供更独特的名称,比如mycheck()和myuncheck(),以防您使用其他使用这些名称的库。

#6


57  

$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();

The last one will fire the click event for the checkbox, the others will not. So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.

最后一个将为复选框触发单击事件,其他的则不会。因此,如果您在onclick事件中为您想要使用的复选框设置了自定义代码,请使用最后一个。

#7


55  

To check a checkbox you should use

检查您应该使用的复选框。

 $('.myCheckbox').attr('checked',true);

or

 $('.myCheckbox').attr('checked','checked');

and to uncheck a check box you should always set it to false:

而且要取消勾选复选框,你应该始终把它设置为false:

 $('.myCheckbox').attr('checked',false);

If you do

如果你做

  $('.myCheckbox').removeAttr('checked')

it removes the attribute all together and therefore you will not be able to reset the form.

它将所有属性移除,因此您将无法重置表单。

BAD DEMO jQuery 1.6. I think this is broken. For 1.6 I am going to make a new post on that.

糟糕的演示jQuery 1.6。我想这个坏了。对于1.6,我将在这方面做一个新的帖子。

NEW WORKING DEMO jQuery 1.5.2 works in Chrome.

新的工作演示jQuery 1.5.2在Chrome中工作。

Both demos use

两个演示使用

$('#tc').click(function() {
    if ( $('#myCheckbox').attr('checked')) {
        $('#myCheckbox').attr('checked', false);
    } else {
        $('#myCheckbox').attr('checked', 'checked');
    }
});

#8


42  

Assuming that the question is...

假设问题是…

How do I check a checkbox-set BY VALUE?

Remember that in a typical checkbox set, all input tags have the same name, they differ by the attribute value: there are no ID for each input of the set.

记住,在一个典型的复选框集合中,所有的输入标记都有相同的名称,它们不同于属性值:设置的每个输入都没有ID。

Xian's answer can be extended with a more specific selector, using the following line of code:

通过使用下面一行代码,可以使用更具体的选择器来扩展Xian的答案:

$("input.myclass[name='myname'][value='the_value']").prop("checked", true);

#9


42  

I'm missing the solution. I'll always use:

我错过了解决方案。我总是使用:

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}

#10


36  

This selects elements that have the specified attribute with a value containing the given substring:

这将选择具有指定属性的元素,其中的值包含给定的子字符串:

$('input[name *= ckbItem]').prop('checked', true);

It will select all elements that contain ckbItem in its name attribute.

它将在其名称属性中选择包含ckbItem的所有元素。

#11


35  

To check a checkbox using jQuery 1.6 or higher just do this:

使用jQuery 1.6或更高版本检查复选框:

checkbox.prop('checked', true);

To uncheck, use:

要取消,请使用:

checkbox.prop('checked', false);

Here' s what I like to use to toggle a checkbox using jQuery:

下面是我使用jQuery来切换复选框的方法:

checkbox.prop('checked', !checkbox.prop('checked'));

If you're using jQuery 1.5 or lower:

如果您使用的是jQuery 1.5或更低:

checkbox.attr('checked', true);

To uncheck, use:

要取消,请使用:

checkbox.attr('checked', false);

#12


32  

Here is a way to do it without jQuery

这里有一种没有jQuery的方法。

function addOrAttachListener(el, type, listener, useCapture) {
  if (el.addEventListener) {
    el.addEventListener(type, listener, useCapture);
  } else if (el.attachEvent) {
    el.attachEvent("on" + type, listener);
  }
};

addOrAttachListener(window, "load", function() {
  var cbElem = document.getElementById("cb");
  var rcbElem = document.getElementById("rcb");
  addOrAttachListener(cbElem, "click", function() {
    rcbElem.checked = cbElem.checked;
  }, false);
}, false);
<label>Click Me!
  <input id="cb" type="checkbox" />
</label>
<label>Reflection:
  <input id="rcb" type="checkbox" />
</label>

#13


27  

Try this:

试试这个:

$('#checkboxid').get(0).checked = true;  //For checking

$('#checkboxid').get(0).checked = false; //For unchecking

#14


24  

Here is code for checked and unchecked with a button:

下面是用按钮检查和检查的代码:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
        });
        set=unset;
    });
});

Update: Here is the same code block using the newer Jquery 1.6+ prop method, which replaces attr:

更新:这里是使用更新的Jquery 1.6+ prop方法的相同代码块,该方法替代了attr:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
        });
        set=unset;
    });
});

#15


23  

If you are using PhoneGap doing application development, and you have a value on the button that you want to show instantly, remember to do this

如果您正在使用PhoneGap进行应用程序开发,并且您希望立即显示的按钮上有一个值,请记住这样做。

$('span.ui-[controlname]',$('[id]')).text("the value");

I found that without the span, the interface will not update no matter what you do.

我发现,如果没有span,无论你做什么,界面都不会更新。

#16


22  

We can use elementObject with jQuery for getting the attribute checked:

我们可以使用jQuery的元素来检查属性:

$(objectElement).attr('checked');

We can use this for all jQuery versions without any error.

我们可以在所有jQuery版本中使用它,而不会出现任何错误。

Update: Jquery 1.6+ has the new prop method which replaces attr, e.g.:

更新:Jquery 1.6+采用新的支持方法替代了attr,例如:

$(objectElement).prop('checked');

#17


21  

Here is the code and demo for how to check multiple check boxes...

下面是如何检查多个复选框的代码和演示。

http://jsfiddle.net/tamilmani/z8TTt/

http://jsfiddle.net/tamilmani/z8TTt/

$("#check").on("click", function () {

    var chk = document.getElementById('check').checked;
    var arr = document.getElementsByTagName("input");

    if (chk) {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = true;
        }
    } else {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = false;
        }
    }
});

#18


19  

Another possible solution:

另一个可能的解决方案:

    var c = $("#checkboxid");
    if (c.is(":checked")) {
         $('#checkboxid').prop('checked', false);
    } else {
         $('#checkboxid').prop('checked', true);
    }

#19


17  

If using mobile and you want the interface to update and show the checkbox as unchecked, use the following:

如果使用mobile,并且您希望接口更新并显示复选框,请使用以下内容:

$("#checkbox1").prop('checked', false).checkboxradio("refresh");

#20


17  

To check and uncheck

检查和取消

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

#21


17  

Be aware of memory leaks in Internet Explorer prior to Internet Explorer 9, as the jQuery documentation states:

在Internet Explorer 9之前,要注意Internet Explorer中的内存泄漏,jQuery文档说明:

In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data().

在版本9之前的Internet Explorer中,使用.prop()将一个DOM元素属性设置为一个简单的原始值(数字、字符串或布尔值),如果不删除该属性,就会导致内存泄漏(使用. removeprop()),然后将DOM元素从文档中删除。要在没有内存泄漏的DOM对象上安全地设置值,请使用.data()。

#22


17  

For jQuery 1.6+

jQuery 1.6 +

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

For jQuery 1.5.x and below

jQuery 1.5。x和下面

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

To check,

检查,

$('.myCheckbox').removeAttr('checked');

#23


15  

$('controlCheckBox').click(function(){
    var temp = $(this).prop('checked');
    $('controlledCheckBoxes').prop('checked', temp);
});

#24


14  

This is probably the shortest and easiest solution:

这可能是最短且最简单的解决方案:

$(".myCheckBox")[0].checked = true;

or

$(".myCheckBox")[0].checked = false;

Even shorter would be:

更短会:

$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;

Here is a jsFiddle as well.

这是一个jsFiddle。

#25


13  

Plain JavaScript is very simple and much less overhead:

简单的JavaScript非常简单,而且开销更少:

var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
    elements[i].checked = true;
}

Example here

例子

#26


12  

When you checked a checkbox like;

当你检查一个复选框的时候;

$('.className').attr('checked', 'checked')

it might not be enough. You should also call the function below;

这可能还不够。你也应该调用下面的函数;

$('.className').prop('checked', 'true')

Especially when you removed the checkbox checked attribute.

特别是当您移除复选框的属性时。

#27


11  

I couldn't get it working using:

我无法使用:

$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');

Both true and false would check the checkbox. What worked for me was:

true和false都将检查复选框。对我起作用的是:

$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', '');     // For unchecking

#28


11  

As @livefree75 said:

作为@livefree75说:

jQuery 1.5.x and below

jQuery 1.5。x和下面

You can also extend the $.fn object with new methods:

您还可以扩展$。fn对象的新方法:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

But in new versions of jQuery, we have to use something like this:

但是在jQuery的新版本中,我们必须使用如下的方法:

jQuery 1.6+

jQuery 1.6 +

    (function($)  {
       $.fn.extend({
          check : function()  {
             return this.filter(":radio, :checkbox").prop("checked", true);
          },
          uncheck : function()  {
             return this.filter(":radio, :checkbox").prop("checked",false);
          }
       });
    }(jQuery));

Then you can just do:

然后你可以这样做:

    $(":checkbox").check();
    $(":checkbox").uncheck();

#29


10  

Here's the complete answer using jQuery

下面是使用jQuery的完整答案。

I test it and it works 100% :D

我测试它,它的效果是100%:D。

    // when the button (select_unit_button) is clicked it returns all the checed checkboxes values 
    $("#select_unit_button").on("click", function(e){

             var arr = [];

             $(':checkbox:checked').each(function(i){
                 arr[i] = $(this).val(); // u can get id or anything else
             });

              //console.log(arr); // u can test it using this in google chrome
    });

#30


10  

In jQuery,

在jQuery中,

if($("#checkboxId").is(':checked')){
    alert("Checked");
}

or

if($("#checkboxId").attr('checked')==true){
    alert("Checked");
}

In JavaScript,

在JavaScript中,

if (document.getElementById("checkboxID").checked){
    alert("Checked");
}
关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/01/08/a1c944efa5e7a2c3caf5263db2f323a.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com