Reputation: 165
Im very, very new to jquery. Im trying to do something that most likely seems elementary to most of the gurus here, but I think I have been messing with it for so long, that I must be overlooking something very simple.
I have a large list of checkboxes (85 in total) that need to be checked based on the value selected in a select list. Both the select list and the checkboxes are created dynamically via an ASP page/database query.
Link to fiddle: http://jsfiddle.net/v9p5C/21/
HTML:
<select id="roleID">
<option data-filter=''>ID</option>
<option data-filter='200'>200</option>
<option data-filter='300'>300</option>
<option data-filter='400'>400</option>
</select>
<BR>
<BR>
<input type="checkbox" data-tags='["200"]'>Create
<br>
<input type="checkbox" data-tags='["200,300"]'>Edit
<br>
<input type="checkbox" data-tags='["200","300, 400"]'>View
<br>
<input type="checkbox" data-tags='["200"]'>Delete
<br>
<input type="checkbox" data-tags='["200"]'>Archive
<br>
SCRIPT:
$(function () {
$(document).on('change', function (e) {
var filter = $(this).data('filter');
$('input[type="checkbox"]').each(function () {
var $checkbox = $(this);
var tags = $checkbox.data('tags');
$.each(tags, function () {
if (filter == this) $checkbox.prop("checked", !$checkbox.prop("checked"));
});
});
});
});
Upvotes: 1
Views: 2752
Reputation: 6044
Your jQuery will need to look more like this:
$(function () {
$('#roleID').on('change', function (e) {
var filter = $(this).val();
$('input[type="checkbox"]').removeAttr('checked');
$('input[type="checkbox"][data-tags*="'+filter+'"]').attr('checked','checked');
});
});
This is a very simple way of creating that functionality. You can view the fiddle here:
http://jsfiddle.net/m0nk3y/kjnoovL0/1/
Upvotes: 2
Reputation: 26406
the var filter = $(this).data('filter');
line was attempting to get the data-filter value from the select element, not the selected option element. Here's how you would grab the selection option's data-filter:
var filter = $('option:selected', this).data('filter');
updated fiddle:
(there were a couple of other minor bugs in the fiddle that are also fixed)
Upvotes: 2