So I have a ul
of checkboxes and I want to allow users to click anywhere on the li
elements to check/uncheck the corresponding checkbox, then apply the changes to the page via javascript. Note that all checkboxes start out checked. This is the layout, excluding a few more li
elements.
<ul class="dropdown-menu">
<li class="cat-header">
<strong>Category</strong>
</li>
<li>
<a class="filter-link"> Red
<input checked="true" class="cat-check" data-filter="red" data-type="color" type="Checkbox">
</a>
</li>
I then try use javascript to alter the page based on the checked
property of the checkboxes. However, I'm getting different values based on how I select the elements. My function looks like this
setFilter = function(checkbox) {
console.log(checkbox);
if ($(checkbox).attr('data-type') === "color") {
if (!$(checkbox).prop('checked')) {
$(checkbox).prop('checked', false);
colorFilter = colorFilter.replace($(checkbox).attr('data-filter') + " ", "");
} else {
$(checkbox).prop('checked', true);
colorFilter = colorFilter + $(checkbox).attr('data-filter') + " ";
}
} else if ($(checkbox).attr('data-type') === "shape") {
if (!$(checkbox).prop('checked')) {
$(checkbox).prop('checked', false);
shapeFilter = shapeFilter + $(checkbox).attr('data-filter') + " ";
} else {
$(checkbox).prop('checked', true);
shapeFilter = shapeFilter.replace($(checkbox).attr('data-filter') + " ", "");
}
}
};
A couple notes. First, color is inclusive (i.e. show it if it has that color) while shape is exclusive (i.e. don't show it if it has that shape) hence the slightly different logic. Second, .prop()
function was returning the opposite values of what I was expecting hence the if (!$(checkbox).prop('checked'))
When I call it like this, it prints out true
$('.filter-link').click(function(e) {
setFilter($(this).children("input")[0]);
});
but when I call it like this, it prints out false
$('.cat-check').click(function(e) {
setFilter($(this)[0]);
});
I tried to reproduce the effect in JSFiddle (https://jsfiddle.net/eg9c4vkv/6/) but was unable to duplicate the effect. I also thought it might be related to console.log (How can I change the default behavior of console.log? (*Error console in safari, no add-on*)) but theoretically the function should be behaving the same as long as the input is the same. Does anyone have any ideas?