Yosra MH
Yosra MH

Reputation: 159

How can I show elements based on the selected option?

Isn't there a better solution than the commented if statement? I'm trying switch case but in this code, I can't hide the div so it's always existing which is wrong. I'm trying to show/hide elements depending on the selected option( it works with if statements but I think there's a cleaner way).

 <div>
       <label>Privileges:</label>
       <select name="privileges" id="privileges" class="" onclick="craateUserJsObject.ShowPrivileges();">
            <option id="all" value="all">All</option>
            <option id="custom" value="custom">Custom</option>
            <option id="test1" value="test1">test1</option>
            <option id="test2" value="test2">tst2</option>
        </select>
    </div>
    <div class="resources" style=" display: none;">resources</div>
    <div class="test1" style=" display: none;">test1</div>
    <div class="test2" style=" display: none;">test2</div>
    <script>
    var Privileges = jQuery('#privileges');
    var select = this.value;

    **/*Privileges.change(function () {
        if ($(this).val() == 'custom') {
            $('.resources').show();
        }
        else $('.resources').hide();
    }); */**
    
    Privileges.change(function () {
    switch($(this).val()){
    case 'custom':
     $('.resources').show();
     break;
     case 'test1':
     $('.test1').show();
     break;
     case 'test2':
     $('.test2').show();
     break;
    }
    });
    </script>

Upvotes: 1

Views: 379

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337713

A more succinct way to do this would be to put a common class on all the div elements you want to toggle so that you can easily hide them on change. In addition, add another class to them which matches the value of the option of they should be displayed when selected. From there you can easily build a selector to hide/show the content. Try this:

var $privileges = jQuery('#privileges');

$privileges.on('change', e => {
  $('.content').hide().filter('.' + e.target.value).show();
});
.content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label>Privileges:</label>
  <select name="privileges" id="privileges">
    <option value="all">All</option>
    <option value="custom">Custom</option>
    <option value="test1">test1</option>
    <option value="test2">tst2</option>
  </select>
</div>
<div class="content custom">resources</div>
<div class="content test1">test1</div>
<div class="content test2">test2</div>

As an aside you should note that in order to follow best practices I moved the inline style attributes on the div to the stylesheet, and I also removed the onclick attribute you had on the select element. The latter should be attached unobtrusively using addEventListener(), if it's needed.

Upvotes: 2

Related Questions