Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 671
Ahmed Fathi Avatar asked Feb 16 '23 23:02

Ahmed Fathi


2 Answers

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

like image 111
adeneo Avatar answered Feb 22 '23 21:02

adeneo


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

like image 23
BenJamin Avatar answered Feb 22 '23 21:02

BenJamin