Hide all contents other than selected

0

I created a javascript code that hides all the different divs from the value that was selected in select .

$(".filter-target").change(function() {
  var target = $(this).val();
  if (target == 0) {
      $('[data-target]').removeClass('hidden');
      return;
  }
  var self = $('[data-target="'+target+'"]');
  $('[data-target]').not(self).toggleClass('hidden');

});

When I select the option that I have displayed the others hide normally, but if I test the others they start to get messy and do not obey the order to "hide all that are not x", the ones that were for appear disappear and come and go. What could be wrong?

    
asked by anonymous 30.08.2016 / 16:59

1 answer

0

What I noticed was that:

  • You forgot to display elements equal to self ;
  • and that you are always switching the "hidden" class, which may end up making elements that were to be invisible as "visible". You could try adding it instead.
var $self = $('[data-target="'+target+'"]');

/* torna os elementos iguais visíveis (caso invisíveis) */
$self.removeClass('hidden');

/* torna os elementos diferentes invisíveis (caso visíveis) */
$('[data-target]').not($self).addClass('hidden');

Note: I can not say, even because I do not use jQuery, but I think that the addClass and removeClass methods already solve the problem of several classes of the same name in an element.

    
30.08.2016 / 17:24