简体   繁体   中英

Show/Hide based on dropdown option

I'm using Jquery to show/hide divs based on what a user selects in a dropdown.

My HTML:

<select>
   <option value='test'>Test</option>
   <option value='example'>Example</option>
   <option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>

My Jquery (in coffeescript):

$("select").on "change", () ->
  shows = $('[data-show="' + $(this).val() + '"]')
  hides = $('[data-hides="' + $(this).val() + '"]')

  shows.show()
  hides.hides()

This works when a user chooses the right option, say Example . But when a user goes back to say Test , it should go back to the default. How do I get this to work?

Can use filter() to set final display and do opposite on whole group before the filter

 $("select").on("change", function(){ var value = this.value // hide all data-show $('[data-show]').hide().filter(function(){ return $(this).data('show') === value; }).show()// only show matching ones $('[data-hide]').show().filter(function(){ return $(this).data('hide') === value; }).hide() }).change()
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value='test'>Test</option> <option value='example'>Example</option> <option value='blah'>Blah</option> </select> <div data-show="blah">Should be shown when blah</div> <div data-hide="example">Should be hidden when example</div>

I dont know what you are up to but this is the described behavior, probably not the desired :D

 $('select').on('change', (e) => { // apply defaults, then filter // credits to filter @charlietfl $('[data-show]').hide().filter('[data-show=' + $(e.target).val() + ']').show(); $('[data-hide]').show().filter('[data-hide=' + $(e.target).val() + ']').hide(); }).change();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value='test'>Test</option> <option value='example'>Example</option> <option value='blah'>Blah</option> </select> <div data-show="blah">Should be shown when blah</div> <div data-hide="example">Should be hidden when example</div>

EDIT added default hide/show

Create a selection of your elements you want to show/hide:

var elements = $('[data-show], [data-hide]');

Then you can use jQuery's .filter function to show only the selected element:

 var elements = $('[data-show], [data-hide]'); function showElement(option) { var filter; // hide all elements befor filtering elements.hide(); // create the filter value, which will be used for filtering switch (option) { case 'test': filter = '[data-hide="example"]'; console.log('show only example'); break; case 'blah': filter = '*'; console.log('show all elements'); break; default: console.log('hide all elements (including example)'); break; } if (filter) { elements.filter(filter).show(); } } showElement('test'); $("select").on("change", function() { showElement($(this).val()); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value='test'>Test</option> <option value='example'>Example</option> <option value='blah'>Blah</option> </select> <div data-show="blah">Should be shown when blah</div> <div data-hide="example">Should be hidden when example</div>

Also you had several typos :

  • When you select the element via data-hide , there's an additional s ( hides ):

     hides = $('[data-hides="' + $(this).val() + '"]')
  • When you want to hide hides via calling .hides() , jQuery only has a .hide() function to hide an element:

     hides.hides()
<select class="selectBoxClass">
    <option value='test'>Test</option>
    <option value='example'>Example</option>
    <option value='blah'>Blah</option>
</select>
<div data-show="blah" class="all ">Should be shown when blah</div>
<div data-hide="example" class="all">Should be hidden when example</div>

<script>
    $(document).on('change', '.selectBoxClass', function(event) {
        event.preventDefault();
        $('div.all').show();
        shows = $('[data-show="' + $(this).val() + '"]')
        hides = $('[data-hides="' + $(this).val() + '"]')
        shows.show()
        hides.hides()
    });

</script>

**if your previous code is not working well, then you can try this.

 $(function(){ $('div').hide(); $('select').change(function(){ if($(this).val()=='blah'){ $('div[data-show]').show(); $('div[data-hide]').hide(); }else if($(this).val()=='example'){ $('div[data-hide]').show(); $('div[data-show]').hide(); }else{ $('div[data-hide]').hide(); $('div[data-show]').hide(); } }) })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select> <option value='test'>Test</option> <option value='example'>Example</option> <option value='blah'>Blah</option> </select> <div data-show="blah">Should be shown when blah</div> <div data-hide="example">Should be hidden when example</div>

Let's assume you assume a set of divs, some of which you wish to show/hide based on what you select in a dropdown list, in jQuery.

This is how it can be achieved.

The grid

<div class="row exhbitors-grid-row">
                            
    <div class="col-lg-6 col-md-6 exhibitor-grid-item" style="">
        <div class="exhibitor-grid-large wow pixFadeRight" data-wow-delay="0.5s" style="visibility: visible; animation-delay: 0.5s; animation-name: pixFadeRight;">
            <div class="member-avater">
                <img src="#" alt="">
            </div>
            <div class="listing-page-exhibitor-brief wow pixFadeUp" style="visibility: visible; animation-name: pixFadeUp;">
                <div class="exhibitor-details">
                    <input type="hidden" name="industry" class="industry Accommodation" value="Accommodation">
                    <h4 class="grid-exhibitor-title">Tourist Board</h4>
                    <strong class="grid-exhibitor-copy">Manning the Booth</strong>
                    <div class="grid-item-host">
                        <span>User</span>
                        <a href="bcard.pdf" target="_blank" title="Download business card"><i class="fa fa-address-card b-card-file" aria-hidden="true"></i>
                        </a> 
                    </div>
                </div>
            </div>
        </div>
    </div>
                
    <div class="col-lg-6 col-md-6 exhibitor-grid-item" style="">
        <div class="exhibitor-grid-large wow pixFadeRight" data-wow-delay="0.5s" style="visibility: visible; animation-delay: 0.5s; animation-name: pixFadeRight;">
            <div class="member-avater">
                <img src="#" alt="">
            </div>
            <div class="listing-page-exhibitor-brief wow pixFadeUp" style="visibility: visible; animation-name: pixFadeUp;">
                <div class="exhibitor-details">
                    <input type="hidden" name="industry" class="industry Airline" value="Airline">
                    <h4 class="grid-exhibitor-title">Tourist Board</h4>
                    <strong class="grid-exhibitor-copy">Manning the Booth</strong>
                    <div class="grid-item-host">
                        <span>User</span>
                        <a href="bcard.pdf" target="_blank" title="Download business card"><i class="fa fa-address-card b-card-file" aria-hidden="true"></i>
                        </a> 
                    </div>
                </div>
            </div>
        </div>
    </div>
    ...
    ...
    ...
    
</div>

Somewhere on the page,you have a dropdown list which looks like this:

<select class="category-select" name="category-select" id="category-select">
    <option value="-1">Industry </option>
    <option value="1">Accommodation</option>
    <option value="2">Airline</option>
    <option value="3">Car Rentals</option>
    <option value="4">City Tourist Board</option>
    ...
    ...
    ...
</select>

On change of this dropdown list, we only want to show the div that has a hidden field value value same as the selected dropdown item. Check the hidden field values above in the div .

We need a small bit of jQuery to do the magic. This is how it will look:

$(document).ready(function(){
if($(".category-select")){
$(".category-select").change(function(){
    $(".exhibitor-grid-item").show();
    var selectedIndustry = $(".category-select option:selected").text();
    $(".exhibitor-grid-item").each(function(){
        var $itemIndustry = $(this).find(".industry").val();
        if($(".category-select option:selected").val() > -1){
          if(selectedIndustry != $itemIndustry){
            $(this).find(".industry").parent().parent().parent().parent().hide();
          }
        }
     });
   });
 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM