Hide div if you do not have multiple classes

1

I have a set of div that I can show or hide by using checkboxes . I am using jQuery to find the div with a certain CSS class, and just display them.

The html is the following:

<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 have is that if I select both blue and green, instead of just a div , it shows all three, since 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 only shows the div that both CSS classes have.

JsFiddle

    
asked by CalvT 12.02.2016 в 12:09
source

1 answer

6

Using map and join can solve the problem easily.

$('input').click(function() {
  $('.tags').hide();
  var marcados = $('input:checked').map(function() { 
     return $( this ).val();
  }).get();
  $('div.' + marcados.join('.')).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

Explanation:

  • $('input:checked').map creates an array based on the value returned in the function, in the case that you pose, as we use $( this ).val() , returns ['azul','verde'] .
  • marcados.join('.') builds a string, separated by points with the elements of marcados , same case is reduced to azul.verde .
  • then, what is contained in both classes is shown: $('div.azul.verde').show();
answered by 12.02.2016 / 12:32
source