Hide element only if visible or vice versa

0

I'm using the change event in a select field, in which the corresponding option is the id of a div, what I'd like to do is display the selected div and hide the other dives only if it is visible or hidden, in a dynamic way if a div that was hidden can be displayed again.

The structure is basically 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>
    
asked by anonymous 29.01.2018 / 04:23

1 answer

1

You can use attributeNotEqual or the :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><selectclass="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><selectclass="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>
    
29.01.2018 / 04:46