Reputation: 20173
I have this selector:
<div class="filterMenu">
<label data-id="5"></label>
<label data-id="2"></label>
</div>
<div class="galeria">
<div data-categories="5,2"></div>
<div data-categories="2,6"></div>
</div>
This is how I'm trying
$('.filterMenu label').on('click', function () {
var id = $(this).data('id');
$('.galeria > div').hide();
$('.galeria > div').each(function () {
var gid = String($(this).data('categories'));
var gidt = gid.split(',');
for ( var i = 0; i < gidt.length; i++) {
if ( gidt[i] == gid ) {
$(this).show();
}
}
});
});
But it won't filter properly,
Any idea?
Upvotes: 0
Views: 69
Reputation: 2131
you can make your code very easier with as @jai said i have tried like this
$('.filterMenu label').on('click', function () {
$('.galeria div').hide()
$('.galeria div[data-categories*="'+ $(this).data('id') +'"]').show();
});
Upvotes: 1
Reputation: 388416
You have a spelling issue with the id check, but you can simplify it to
var $galerias = $('.galeria > div');
$('.filterMenu label').on('click', function() {
var id = $(this).data('id') + '';
$galerias.each(function() {
var $this = $(this);
var gidt = ($this.data('categories') + '').split(',');
$this.toggle(gidt.indexOf(id) > -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="filterMenu">
<label data-id="5">5</label>
<label data-id="2">2</label>
</div>
<hr />
<div class="galeria">
<div data-categories="5,2">5,2</div>
<div data-categories="2,6">2,6</div>
<div data-categories="6">6</div>
<div data-categories="5">5</div>
<div data-categories="2">2</div>
<div data-categories="2,5,6">2,5,6</div>
</div>
Or
var $galerias = $('.galeria > div');
$('.filterMenu label').on('click', function() {
var id = $(this).data('id');
$galerias.each(function() {
var $this = $(this);
var gidt = $this.data('categories');
$this.toggle(gidt.indexOf(id) > -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="filterMenu">
<label data-id="5">5</label>
<label data-id="2">2</label>
</div>
<hr />
<div class="galeria">
<div data-categories="[5,2]">5,2</div>
<div data-categories="[2,6]">2,6</div>
<div data-categories="[6]">6</div>
<div data-categories="[5]">5</div>
<div data-categories="[2]">2</div>
<div data-categories="[2,5,6]">2,5,6</div>
</div>
Upvotes: 1
Reputation: 2108
Should your code not be:
if (gidt[i] == id) {
$(this).show();
}
instead of:
if (gidt[i] == gid) {
$(this).show();
}
Upvotes: 2
Reputation: 74738
You could try something like this:
$('.filterMenu label').on('click', function () {
var id = $(this).data('id');
$('.galeria > div').hide();
$('.galeria > div[data-categories*="'+id+'"]').show();
});
Upvotes: 2