Ahmed Fathi
Ahmed Fathi

Reputation: 179

Check Checkboxes based on values in an Array

Checkbox check with Array or values

Html Code:

<div id="weekdays">
<label for="saturday">  Saturday    </label><input type='checkbox' name='week_day[]' value='saturday'  id="saturday">   
<label for="sunday">    Sunday      </label><input type='checkbox' name='week_day[]' value='sunday'    id="sunday"> 
<label for="monday">    Monday      </label><input type='checkbox' name='week_day[]' value='monday'    id="monday"> 
<label for="tuesday">   Tuesday     </label><input type='checkbox' name='week_day[]' value='tuesday'   id="tuesday">    
<label for="wednesday"> Wednesday   </label><input type='checkbox' name='week_day[]' value='wednesday' id="wednesday">  
<label for="thursday">  Thursday    </label><input type='checkbox' name='week_day[]' value='thursday'  id="thursday">   
<label for="friday">    Friday      </label><input type='checkbox' name='week_day[]' value='friday'    id="friday"> 

Array

var f = ["saturday", "sunday", "monday"] 

info I wanna check the days saturday, sunday and monday on this form

Upvotes: 4

Views: 5759

Answers (3)

BenJamin
BenJamin

Reputation: 783

With the forEach method of Array this is very simple even without JQuery.

f.forEach(function(i){
  document.getElementById(i).checked = true;
});

You can read more about for each on the Mozilla Developer Network

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

One simple way is iterate over the array and use prop method along with id selector.

for(var i=0;i<f.length;i++) {
    $('#' + f[i]).prop('checked', true)
}

Check Fiddle

Upvotes: 1

adeneo
adeneo

Reputation: 318182

A jQuery selector is nothing but a string, so just join the array into a string of ID's :

$('#'+f.join(', #')).prop('checked', true);

FIDDLE

Upvotes: 6

Related Questions