I have a set of div
that I can show or hide by using checkboxes
. I'm using jQuery to find the div
ones with a certain CSS class, and just display them.
The html is as follows:
<div class="inputs">
<input class="filterbox" type="checkbox" value="azul" />Azul
<input class="filterbox" type="checkbox" value="verde" />Verde
<input class="filterbox" type="checkbox" value="rojo" />Rojo
</div>
<br>
<div class="tags azul">Azul</div>
<div class="tags verde azul">Verde y Azul</div>
<div class="tags verde rojo">Verde y Rojo</div>
Javascript/jQuery
$('input').click(function() {
$('.tags').hide();
$('input:checked').each(function(i) {
$('div.' + $(this).val()).show();
});
});
The problem I'm having is that if I select both blue and green, instead of just one div
, it shows all three, since they all div
have the blue or green CSS class.
What I want to do is edit the code so that when I select more than one checkbox
it just shows the ones div
that have both CSS classes.
Using map and join you can easily solve the problem.
Explanation:
$('input:checked').map
creates an array based on the value returned in the function, in the case you propose, as we use$( this ).val()
, returns['azul','verde']
.marcados.join('.')
builds a dot-separated string with the elements ofmarcados
, same case reduces toazul.verde
.$('div.azul.verde').show();