Trying to build a filter. There is an item list with a static item class, and dynamically generated item class.
<div class="itemswrap">
<div class="item dynamic1"></div>
<div class="item dynamic2"></div>
<div class="item dynamic3"></div>
<div class="item dynamic2"></div>
</div>
There is also a filter menu in a sidebar with dynamically generated id's
<ul class="subnav">
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic1" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic2" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic3" />
<label for="dynamic1">whatever label</label>
</li>
</ul>
The idea is to match filter id's with item classes and once a checkbox is checked, only divs with the matching class should be visible.
Here is a js code i came up with
$(".lifilter").each(function(){
var filter1 = $(this).find('.filtercheck').attr('id');
if ( $(this).find('input.filtercheck').attr('checked') )
{
$(".itemswrap .item").hide();
$('.' + filter1).show();
}
});
And nothing happens...
I think that you want to show/hide divs on any checkbox state change. Try to wrap your code in the change
event of you checkboxes :
$(".filtercheck").on('change', function(){
$(".lifilter").each(function(){
var filter1 = $(this).find('.filtercheck').attr('id');
if ($(this).find('input.filtercheck').attr('checked')) {
$(".itemswrap .item").hide();
$('.' + filter1).show();
}
});
});
How 'bout this:
function refreshDynamicDivs() {
$(".filtercheck").each(function() {
var id = $(this).attr("id");
if($(this).is(":checked")) {
$("."+id).show();
}
else {
$("."+id).hide();
}
});
}
The issue is because checked does not return a boolean value use prop instead, but in your case you can use :checked
pseudo and check the result length.
Code:
$("button").click(function () {
$(".itemswrap .item").hide();
$(".lifilter").each(function () {
var filter1 = $(this).find('.filtercheck').attr('id');
if ($(this).find('input.filtercheck:checked').length>0) {
$('.' + filter1).show();
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.