jquery 设置复选框已选中

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

jquery set checkbox checked

jquerycheckbox

提问by psopa

I already tried all the possible ways, but I still didn't get it working. I have a modal window with a checkboxI want that when the modal opens, the checkboxcheck or uncheck should be based on a database value. (I have that already working with others form fields.) I started trying to get it checked but it didn't work.

我已经尝试了所有可能的方法,但仍然无法正常工作。我有一个模态窗口,checkbox我希望当模态打开时,checkbox选中或取消选中应该基于数据库值。(我已经与其他表单字段一起工作了。)我开始尝试检查它,但它没有用。

My html div:

我的 html div:

<div id="fModal" class="modal" >
    ...
    <div class="row-form">
        <div class="span12">
            <span class="top title">Estado</span>

          <input type="checkbox"  id="estado_cat" class="ibtn">
       </div>
    </div>             
</div>

and the jquery:

和jQuery:

$("#estado_cat").prop( "checked", true );

I also tried with attr, and others seen here in the forums, but none seem to work. Can someone point me the right way?

我也尝试过attr,以及在论坛中看到的其他人,但似乎都不起作用。有人可以指出我正确的方法吗?

EDIT: ok, I'm really missing something here... I can check/uncheck using code if the check box is in the page, but is it's in the modal window, I can't. I tried dozens of different ways...

编辑:好的,我真的在这里遗漏了一些东西......如果复选框在页面中,我可以使用代码选中/取消选中,但它是否在模式窗口中,我不能。我尝试了几十种不同的方法......

I have a link that's supposed to open the modal:

我有一个应该打开模态的链接:

and jquery to "listen" the click and execute some operations like filling some text boxes with data coming from database. Everything works like I want but the problem is that I can't set checkbox checked/unchecked using code. help please!

和 jquery 来“监听”点击并执行一些操作,比如用来自数据库的数据填充一些文本框。一切都像我想要的那样工作,但问题是我无法使用代码设置复选框选中/取消选中。请帮忙!

$(function() {
 $(".editButton").click(function(){
       var id = $(this).data('id'); 
       $.ajax({
          type: "POST",
          url: "process.php",
          dataType:"json",
          data: { id: id, op: "edit" },
        }).done(function( data ) {
//the next two lines work fine, i.e., it grabs the value from database and fills the textboxes
          $("#nome_categoria").val( data['nome_categoria'] );
          $("#descricao_categoria").val( data['descricao_categoria'] );
//then I tried to set the checkbox checked (because its unchecked by default) and it does not work
           $("#estado_cat").prop("checked", true);
        $('#fModal').modal('show');
});
    evt.preventDefault();
    return false;
    });     
});

回答by singe Batteur

you have to use the 'prop' function :

您必须使用“道具”功能:

.prop('checked', true);

Before jQuery 1.6(see user2063626's answer):

在 jQuery 1.6 之前(参见user2063626 的回答):

.attr('checked','checked')

回答by eriknoyes

Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true)and .prop("checked", false) were the correct solution.

获取所有建议的答案并将它们应用于我的情况 - 尝试根据检索到的 true(应选中该框)或 false(不应选中该框)值来选中或取消选中一个复选框 - 我尝试了上述所有方法并且发现使用.prop("checked", true).prop("checked", false) 是正确的解决方案。

I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.

我还不能添加评论或添加答案,但我觉得这很重要,可以添加到对话中。

Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":

这是完整日历修改的普通代码,说明如果检索到的值“allDay”为真,则选中 ID 为“even_allday_yn”的复选框:

if (allDay)
{
    $( "#even_allday_yn").prop('checked', true);
}
else
{
    $( "#even_allday_yn").prop('checked', false);
}

回答by eriknoyes

Dude try below code :

伙计尝试下面的代码:

$("div.row-form input[type='checkbox']").attr('checked','checked')

OR

或者

$("div.row-form #estado_cat").attr("checked","checked");

OR

或者

$("div.row-form #estado_cat").attr("checked",true);

回答by shadock

"checked" attribute 'ticks' the checkbox as soon as it exists. So to check/uncheck a checkbox you have to set/unset the attribute.

“checked”属性会在复选框存在时“勾选”复选框。因此,要选中/取消选中复选框,您必须设置/取消设置属性。

For checking the box:

勾选复选框:

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

For unchecking the box:

要取消选中该框:

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

For testing the checked status:

用于测试选中状态:

if ($('#myCheckbox').is(':checked'))

Hope it helps...

希望能帮助到你...

回答by KeyOfJ

Since you are in a modal window (whether dynamic or in the page) you can use the following code to accomplish your goal: (I ran into the same problem on my site and this is how I fixed it)

由于您处于模式窗口(无论是动态窗口还是页面中),您可以使用以下代码来实现您的目标:(我在我的网站上遇到了同样的问题,这就是我修复它的方式)

HTML:

HTML:

<div class="content-container" style="text-align: right;">
    <input type="checkbox" id="QueryGroupCopyQueries">
    <label for="QueryGroupCopyQueries">Create Copies</label>                                                   
</div>

CODE:

代码:

$.each(queriesToAddToGroup, function (index, query) {
    if (query.groupAddType === queriesGroupAddType.COPY) {

        // USE FIND against your dynamic window and PROP to set the value
        // if you are using JQUERY 1.6 or higher.
        $(kendoWindow).find("input#QueryGroupCopyQueries").prop("checked", true);

        return;
    }

In the above "kendoWindow" is my window (mine is dynamic, but I also do this when appending to an element directly in the page). I am looping through an array of data ("queriesToAddToGroup") to see if any rows have an attribute of COPY. If so I want to turn on the checkbox within the window that sets that attribute when a user saves from this window.

在上面的“kendoWindow”中是我的窗口(我的窗口是动态的,但在直接附加到页面中的元素时我也会这样做)。我正在遍历数据数组(“queriesToAddToGroup”)以查看是否有任何行具有 COPY 属性。如果是这样,我想打开窗口中的复选框,当用户从此窗口保存时设置该属性。

回答by user1849310

.attr("checked",true)
.attr("checked",false)

will work.Make sure true and false are not inside quotes.

会起作用。确保 true 和 false 不在引号内。

回答by Subir

You can write like below given code.

您可以像下面给出的代码一样编写。

HTML

HTML

<input type="checkbox"  id="estado_cat" class="ibtn">

jQuery

jQuery

$(document).ready(function(){
    $(".ibtn").click(function(){
        $(".ibtn").attr("checked", "checked");
    });
});

Hope it work for you.

希望它对你有用。

回答by lordcheeto

If you're wanting to use this functionality for a GreaseMonkey script to automatically check a checkbox on a page, keep in mind that simply setting the checked property may not trigger the associated action. In that case, "clicking" the checkbox probably will (and set the checked property as well).

如果您想将此功能用于 GreaseMonkey 脚本以自动选中页面上的复选框,请记住,仅设置 checked 属性可能不会触发相关操作。在这种情况下,“单击”复选框可能会(并设置 checked 属性)。

$("#id").click()

回答by Arvin

$("#divParentClip").find("#subclip_checkbox")[0].checked=true;

Find will return array , so use [0] to get even if there is only one item

Find 将返回 array ,因此即使只有一项,也可以使用 [0] 来获取

if you don't use find then

如果你不使用 find 那么

$("#subclip_checkbox").checked=true;

this worked fine in Mozilla Firefox for me

这对我来说在 Mozilla Firefox 中运行良好

回答by Sergio Pulgarin

Worked for me:

为我工作:

$checkbok.prop({checked: true});