how do you show only the stores in the selected neighborhood?

0

When I clicked on neighborhood 1, all div (store class) that did not belong to this neighborhood would be in display: none. can have several neighborhoods so I wanted a way that I did not need to update every time I had a new neighborhood

<div>
   <p>Bairro 1</p>
   <p>Bairro 2</p>
   <p>Bairro 3</p>
   <p>Bairro 4</p>
</div>

<div class="loja">
   <p>Bairro 1</P>
</div>

<div class="loja">
   <p>Bairro 2</P>
</div>

<div class="loja">
   <p>Bairro 3</P>
</div>

<div class="loja">
   <p>Bairro 4</P>
</div>
    
asked by anonymous 23.01.2016 / 16:44

2 answers

1

Ney, you do just like this:

$('.selectBairro p').click(function(){
  var bairro = $(this).text();
  $('.loja').hide();
  $('.loja p:contains(' + bairro + ')').parent().show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="selectBairro">
   <p>Bairro 1</p>
   <p>Bairro 2</p>
   <p>Bairro 3</p>
   <p>Bairro 4</p>
</div>
<hr>
<div class="loja">
   <p>Bairro 1</p>
</div>

<div class="loja">
   <p>Bairro 2</p>
</div>

<div class="loja">
   <p>Bairro 3</p>
</div>

<div class="loja">
   <p>Bairro 4</p>
</div>

I use the :contains() selector.

But this method works only if your store has a paragraph with the name of the neighborhood. It is not very manipulative because of its method of choosing. But for what you have, that one does.

To be more selective, add a class="name" to each paragraph with the neighborhood name, so you can do instead:

  $('.loja p:contains(' + bairro + ')').parent().show();

That:

  $('.loja .name:contains(' + bairro + ')').parent().show();
    
23.01.2016 / 16:54
2

You can do this with native JavaScript like this: link

function getElements(sel) {
    var els = document.querySelectorAll(sel);
    return [].slice.call(els);
}

function procurar(e) {
    var procurado = e.target.innerHTML;
    bairros.forEach(function(el) {
        el.parentNode.style.display = el.innerHTML == procurado ? 'block' : 'none';
    });
}

var escolhas = getElements('div:first-of-type > p');
var bairros = getElements('.loja > p');

escolhas.forEach(function(el) {
    el.addEventListener('click', procurar);
});

Your HTML can lead to problems, you have to make sure you have exactly the same HTML. The best thing would be to use classes or attributes data- to know better which elements to select ...

    
23.01.2016 / 17:01