javascriptjqueryarrayshtml-selectselected

How to make selected checkboxes with using array for data?


I have 7 checkbox's for day selection. For example:

<span><input name="days" type="checkbox" value="1" id="day1"><label for="day1">M</label></span>
<span><input name="days" type="checkbox" value="2" id="day2"><label for="day2">T</label></span>
<span><input name="days" type="checkbox" value="3" id="day3"><label for="day3">W</label></span>
<span><input name="days" type="checkbox" value="4" id="day4"><label for="day4">T</label></span>
<span><input name="days" type="checkbox" value="5" id="day5"><label for="day5">F</label></span>
<span><input name="days" type="checkbox" value="6" id="day6"><label for="day6">S</label></span>
<span><input name="days" type="checkbox" value="7" id="day7"><label for="day7">S</label></span>

And I also have an array :

var selectedDays = ["5","6"];

I want the 5th and 6th days to be selected on load. Any short way to do this?


Solution

  • $(document).ready(function () {
      $.each(selectedDays, function(i, val) {
        $('#day'+val).prop('checked', true);
      });
    });