Hide element only if visible or vice versa

Asked

Viewed 127 times

0

I’m wearing the event change in a select field, where the corresponding option is the id of a div, what I would like to do is to display the selected div and hide the rest only if it is visible or hidden, in a dynamic way if a hidden div can be displayed again.

the structure basically is this:

<select class="form-control" name="template">
   <option value="template1">Template 1</option>
   <option value="template2">Template 2</option>
</select>
<div id="template1">tema 1</div>
<div id="template2">tema 2</div>

1 answer

1


You can use attributeNotEqual or the method :not()

attributeNotEqual

$('select[name="template"]').on('change', function() {
  var id = $(this).val();
  // Oculta as DIV's menos a selecionada
  $('div.template[id!="'+id+'"]').hide();
  // Caso a DIV selecionada esteja oculta, exibe
  $('div.template[id="'+id+'"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="template">
   <option value="template1">Template 1</option>
   <option value="template2">Template 2</option>
</select>

<div class="template" id="template1">tema 1</div>
<div class="template" id="template2">tema 2</div>

:not()

$('select[name="template"]').on('change', function() {
  var id = $(this).val();
  // Oculta as DIV's menos a selecionada
  $('div.template:not([id="'+id+'"])').hide();
  // Caso a DIV selecionada esteja oculta, exibe
  $('div.template[id="'+id+'"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="template">
   <option value="template1">Template 1</option>
   <option value="template2">Template 2</option>
</select>

<div class="template" id="template1">tema 1</div>
<div class="template" id="template2">tema 2</div>

  • For some reason when I select any option the whole page is hidden kk

  • If so: $('[id!="'+id+'"]').hide(); will hide everything, must be like this: $('div[id!="'+id+'"]').hide(); informing that the element is the DIV

  • still continues, I think it has become generic, it covers all Divs

  • See I made a modification, added the attribute class.

  • now yes, thank you :)

Browser other questions tagged

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