简体   繁体   English

jQuery查找复选框并选中/取消选中它

[英]jQuery find checkbox and check/uncheck it

My checkboxes created in loop: 我的循环创建的checkboxes

@foreach (L1 item in Model)
{
    <li><label class="checkbox"><input type="checkbox" id="@(item.Name)" 
         class="clink" value="@(item.Name)"/>@item.ForeName</label></li>
}

And then I am using jQuery to check it: 然后我使用jQuery来检查它:

 $('#cworks').prop('checked', true);

The above is not working. 以上不起作用。 here is the generated html using firebug 这是使用firebug生成的html

<label class="checkbox"><input id="cworks" class="clink" value="cworks" type="checkbox">cworks</label>

如果复选框有“id”,那么您只需选择它即可。

$('#Careworks_Map').prop('checked', true);

ID's should be unique. ID应该是唯一的。 So it's enough (and most efficient) to use that ID as a selector: 因此,将该ID用作选择器就足够了(而且效率最高):

$('#Careworks_Map').prop('checked', true);

You are using an id selector while you have to use a class selector : 您必须使用类选择器时使用id选择器:

$('.checkbox input[id="Careworks_Map"]').prop('checked', true);

You can also select directly the id of the checkbox you want to modify: 您还可以直接选择要修改的复选框的ID:

$('#Careworks_Map').prop('checked', true);
$(":checkbox input[id='Careworks_Map']").attr("checked", true);

It's not working because the <label> is declaring a class="checkbox" so you need to search for class with a period . 它不起作用,因为<label>声明了一个class="checkbox"所以你需要搜索带有句点的类. and then target the inner checkbox 然后定位内部复选框

$('#checkbox input[id="Careworks_Map"]').prop('checked', true); // wrong

$('.checkbox input[id="Careworks_Map"]').prop('checked', true); // right

In your example you set a class class="checkbox" then in the jquery call you use an id #checkbox input so to make it work you should do: 在你的例子中你设置了一个class class="checkbox"然后在jquery调用中你使用了一个id #checkbox input所以为了使它工作,你应该这样做:

$('.checkbox input[id="somestring"]').prop('checked', true);

Then if your item.Name is set with a prefix like var item.Name = my_prefix _somestring you can use a wildcard. 然后,如果您的item.Name设置为类似var item.Name = my_prefix _somestring的前缀,则可以使用通配符。

 $('.checkbox input[id=*"my_prefix"]').prop('checked', true);

If item.Name are unique (which I presume) then just do : 如果item.Name是唯一的(我假设),那么就这样做:

$('#Careworks_Map').prop('checked', true);

EDIT 编辑

based on your update you should do that : 根据您的更新,您应该这样做:

$('#cworks').prop('checked', true);

http://jsfiddle.net/daguru/7FUBn/2/ http://jsfiddle.net/daguru/7FUBn/2/

Use id instead of class 使用id而不是class

$('#Careworks_Map').prop('checked', true); $('#Careworks_Map')。prop('checked',true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM