4

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

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldnt the comma be before the #?
@Karl-AndréGagnon - yes it should, just realized it myself.
1

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

4 Comments

i try it into modal form it not working , do you have any idea ? info : i use jqueryUi
happy to take a look if you are still having trouble, would you like to throw a fiddle together?
What if my array changed??? For example i am getting this array with a button click and just think array items change randomly. How to uncheck other checkboxes??
if you're wanting to un-check boxes you'll want to iterate over each time and assign checked to true/false based on if its in the new array.
1

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

1 Comment

I think you meant true not false?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.