按值匹配复选框

时间:2013-01-24 13:24:09

标签: javascript jquery asp.net checkbox

我有一个复选框列表,我试图根据文本框的值来检查这些复选框。

var codes = $('#textbox1').val().split(','); // this contains [ "Dept1" and "Dept2" ]
var allDeptChecks = $('.Dept-help input:checkbox'); // this contains all of my checkboxes
allDeptChecks.attr('checked', false);
$.each(codes, function() {
    var chkDept = allDeptChecks.find("[value='"+this+"']"); // no matter what I try, this selector matches 0 elements
    chkDept.attr('checked', true);
}); 

<li title="Dept 1">
    <input type="checkbox" name="chkDept1" value="Dept1">
    <span>Dept1</span>
    <span>Description Numero Uno</span>
</li>
<li title="Dept 2">
    <input type="checkbox" name="chkDept2" value="Dept2">
    <span>Dept2</span>
    <span>Description Numero Dos</span>
</li>

不应该这样做吗?

编辑: Here's a JSFiddle

2 个答案:

答案 0 :(得分:1)

你去吧

$('#lnkGo').click(function () {
    var codes = $('#textbox1').val().split(','); // this contains [ "Dept1" and "Dept2" ]
    var allDeptChecks = $('input:checkbox'); // this contains all of my checkboxes
    allDeptChecks.prop('checked', false);
    $.each(codes, function () {
        var chkDept = allDeptChecks.filter("input[value='" + this + "']"); // no matter what I try, this selector matches 0 elements
        chkDept.prop('checked', true);
    });
});

答案 1 :(得分:1)

试试这个:

$.each(codes, function(i, value) {
$("input[value='"+value+"']").prop('checked', true);    
});