Echilon
Echilon

Reputation: 10244

Matching Checkboxes By Value

I have a list of checkboxes, I'm trying to check these based on the value of a textbox.

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>

Shouldn't this work?

EDIT: Here's a JSFiddle

Upvotes: 1

Views: 211

Answers (2)

Pitchai P
Pitchai P

Reputation: 1317

Try this :

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

Upvotes: 1

Zach
Zach

Reputation: 3207

Here you go

$('#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);
    });
});

Upvotes: 1

Related Questions