April 2, 2012

Fastest way to checked checkboxes that have a value of specific list in jQuery

Question by Saeid

This is My HTML Dom:

<input type="checkbox" class="chk-act" name="actionChk" value="17">
<input type="checkbox" class="chk-act" name="actionChk" value="18">
<input type="checkbox" class="chk-act" name="actionChk" value="19">
<input type="checkbox" class="chk-act" name="actionChk" value="20">
<input type="checkbox" class="chk-act" name="actionChk" value="21">

And I have a jQuery script that returned a JSon response by ajax:

["18","20","21"]

The list can be as long as up to 200 members. So I am interested to find out the fastest way to checked checkboxes, that have a value in above list, when the response is returned. What is your suggestion?

Answer by Jibi Abraham

The fastest way would be to add an id identifier to your list of checkboxes. For example –

<input type="checkbox" class="chk-act" name="actionChk" value="17" id='chk-act-17' />
//incidentally, I hope the lack of a closing '/' was an oversight
//when you get your JSON response, in your ajax success or done methods
var resp = ["12", "232"],
    respLength = resp.length;
for(var i = 0; i < respLength; i += 1){
    $('#chk-act-' + resp[i]).prop('checked', true);
    //if your are using jquery 1.7+ that is, otherwise use, 
    $('#chk-act-' + resp[i]).attr('checked', 'checked');
}

JS Perf Tests

Comparing the two current answers, the OP’s requirement of “fastest” would be better served by going down the uglier ‘id‘ implementation.
Js Perf

FIddle added

JS FIddle

Posting code from fiddle-

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
    checkboxes = $('.chk');

checkboxes.each(function(i, item){
    $(this).prop('checked', false);
});

arr.forEach(function(item, i) {
    $('#chk_' + item).prop('checked', true);
});

Answer by Starx

Mixing jQuery on this

arr = ["18","20","21"];
$("input:checkbox").prop('checked', false); //If you need to uncheck other boxes too
$.each(arr, function(k,v) {       
   $("input[value=""+v+""]").prop('checked', true);
});

Demo 1 | Demo 2: with all other checks removed

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!