Jquery 如何根据值选中输入框

Jquery 如何根据值选中输入框,jquery,Jquery,假设我有下面的html <input type="checkbox" name="products" value="1" id="product_1" /> <input type="checkbox" name="products" value="2" id="product_2" /> <input type="checkbox" name="products" value="3" id="product_3" /> 现在我被如何检查列表中的值是否匹配的

假设我有下面的html

<input type="checkbox" name="products" value="1" id="product_1" />
<input type="checkbox" name="products" value="2" id="product_2" />
<input type="checkbox" name="products" value="3" id="product_3" />

现在我被如何检查列表中的值是否匹配的复选框所困扰。在我的示例中,第一个和第二个输入将在就绪时检查。

尝试使用id选择器,因为id包含值

var list = [1, 2];
$.each(list, function (i, val) {
    $('#product_' + val).prop('checked', true)
})
演示:

如果您正在执行重置操作,则

var list = [1, 2];
$('input[name="products"]').prop('checked', function () {
    return $.inArray(parseInt(this.value), list) > -1
})

演示:

您可以遍历值数组,然后根据产品ID检查每个输入

list.forEach(function(item) {
    $('#product_'+ item).prop('checked', true);
});
一个更高级的解决方案是构建一个选择器,然后一次检查所有选择器

$( list.map(function(item) {
    return '#product_'+ item;
}).join(',') ).prop('checked', true);

您可以试试这个,您可以使用id属性
product.*
作为选择器

var list = [1,2];

$.each(list,function( index, value ) {
   // alert( index + ": " + value );
    $("#product_"+value).prop('checked', true);
});
演示:

试试这个

HTML


我会这样做:

$('[name=products][value=' + list.join('],[name=products][value=') + ']').prop('checked', true);
你可以用


你试过什么吗?
$('product'+list.join(','product')).prop('checked',true)->字段名不是
产品[]
,但可能应该是。;)
<input type="checkbox" name="products[]" value="1" id="product_1" />
<input type="checkbox" name="products[]" value="2" id="product_2" />
<input type="checkbox" name="products[]" value="3" id="product_3" />
var list = [1, 2];
$("input[name='products[]']").each( function(i,j) {
if(jQuery.inArray(parseInt($(this).val()), list)!= -1){
$(j).attr('checked', 'checked'); //OR $(j).prop('checked', true);
}
});
$('[name=products][value=' + list.join('],[name=products][value=') + ']').prop('checked', true);
var list=[1,2];
    $('input[name=products]').each(function(){
                  if(jQuery.inArray(parseInt($(this).val()), list)!=-1)
           {
               $(this).prop('checked', true);
           }
    });
$('input[name=products]').prop('checked', function() {
  return (list.indexOf(~~this.value) != -1);
});