Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check multiple checkboxes using jquery

Tags:

jquery

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.

Thank you in advance to helpers.

like image 205
Sohil Desai Avatar asked Sep 04 '13 13:09

Sohil Desai


People also ask

How do you checked multiple checkbox in jQuery?

$('#CheckAll'). change(function(){ if ($(this).is(":checked")) { $('. checkboxes'). each(function(){ $(this).

How do I get multiple checkbox values?

Read Multiple Values from Selected CheckboxesUse the foreach() loop to iterate over every selected value of checkboxes and print on the user screen. <? php if(isset($_POST['submit'])){ if(! empty($_POST['checkArr'])){ foreach($_POST['checkArr'] as $checked){ echo $checked.


2 Answers

Try

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

Demo: Fiddle

like image 195
Arun P Johny Avatar answered Oct 03 '22 04:10

Arun P Johny


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/

like image 38
Blazemonger Avatar answered Oct 03 '22 06:10

Blazemonger