使用 jquery 检查多个复选框

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

Check multiple checkboxes using jquery

jquery

提问by Sohil Desai

I have an array something like

我有一个类似的数组

var values = ['1','3','4','5'];

I have the list of checkboxes

我有复选框列表

<div id='list'>
    <input type='checkbox' value='1' />
    <input type='checkbox' value='2' />
    <input type='checkbox' value='3' />
    <input type='checkbox' value='4' />
    <input type='checkbox' value='5' />
    <input type='checkbox' value='6' />
    <input type='checkbox' value='7' />
    <input type='checkbox' value='8' />
    <input type='checkbox' value='9' />
    <input type='checkbox' value='10' />
</div>

now I want to select checkboxes whose values lies within array values. I have done this

现在我想选择其值位于数组值内的复选框。我已经这样做了

for(var i = 0; i < values.length; i++)
    $("#list [value=" + values[i] + "]").attr("checked", "checked");

it is working fine but can I do it without for loop.

它工作正常,但我可以在没有 for 循环的情况下做到这一点。

Thank you in advance to helpers.

在此先感谢帮助者。

回答by Arun P Johny

Try

尝试

$("#list").find('[value=' + values.join('], [value=') + ']').prop("checked", true);

Demo: Fiddle

演示:小提琴

回答by Blazemonger

You could do this even more succinctly with a single combined selector:

您可以使用单个组合选择器更简洁地执行此操作:

$('#list [value="'+values.join('"],[value="')+'"]').prop('checked',true);

Which produces a selector like:

它产生一个选择器,如:

$('#list [value="1"],[value="3"],[value="4"],[value="5"]')

http://jsfiddle.net/mblase75/jgqm4/

http://jsfiddle.net/mblase75/jgqm4/

回答by Selvakumar Arumugam

You could use filterlike below, but it is same as forloop though..

你可以filter像下面这样使用,但它与for循环相同..

$('#list :checkbox').filter(function () {
    return $.inArray(this.value, values) >= 0;
}).prop('checked', true);

回答by Daniel

You can replace your for-loop with $.each

你可以用 $.each 替换你的 for 循环

JQuery

查询

$.each(values, function() {
  $("#list [value=" + this + "]").attr("checked", "checked");
});