How do you show only the shops of the selected neighborhood?

Asked

Viewed 44 times

0

When clicked in the neighborhood 1, all div(store class) that did not belong to that neighborhood would be on display:None. may have several neighborhoods so wanted a way that did not need to update every time 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>

2 answers

2

You can do this with native Javascript like this: https://jsfiddle.net/o9jbcq7x/

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 give rise to problems, you have to make sure you have exactly the same HTML. The best would be to use classes or attributes data- to better know which elements to select...

1


Ney, you just do 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>
<div class="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 selector :contains().

But this method only works if your store has a paragraph with the name of the neighborhood. It is not something very manipulable due to your method of choosing. But for what you have, this one.

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

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

That:

  $('.loja .name:contains(' + bairro + ')').parent().show();
  • Thanks again Thanks :) I will do this method that you said yes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.