Using SQL 2008 Server and the latest JQuery. If I query a column from the database and get the list/array how do I mark the checkboxes in each checkbox group ‘checked’? Example checkbox groups and lists below:
list for category ‘1,7,20’ (Jquery should mark checkboxes with values 1,7,10 checked)
list for likes ‘2,3’ (Jquery should mark checkboxes with values 2 and 3 checked)
<form>
<input type="checkbox" class="category" name="category" value="14" />Blah
<input type="checkbox" class="category" name="category" value="1" />Blah1
<input type="checkbox" class="category" name="category" value="7" />Blah2
<input type="checkbox" class="category" name="category" value="20" />Blah3
<input type="checkbox" class="likes" name="likes" value="17" />Apple
<input type="checkbox" class="likes" name="likes" value="3" />Apple1
<input type="checkbox" class="likes" name="likes" value="2" />Apple2
<input type="checkbox" class="likes" name="likes" value="13" />Apple3
</form>
I tried the following JQuery code, but it doesn’t work:
$.each(['1,7,20'], function (index, item) {
if ($('.category').val() === item) {
$(".category").prop("checked", true);
}
});
You’re passing an array with a single element that is the string
1,7,20, not an array with three elements that are the strings1,7and20, so I’m not sure why you’re expecting it to work. If your input is in fact the string, you can split it on the comma to get an array with your numbers as strings:Then pass
myArrayto the$.each()function call.There’s also a problem with the code inside the function you’ve passed to
$.each(). If you do call.val()on a jQuery object containing multiple elements, it will usually return the value for the first element only. You’ll need to iterate again over the collection of elements, and usethisto refer to the current element.