简体   繁体   中英

JQuery - Show Hide DIVS based on 2 different select drop down values

I have created 2 select drop downs, and have it show/hide a div. However I want to base my div depending on 2 values which will be selected from 2 separate drop downs.

See below my working code, to show the div/show hide based on one value, I need to filter this again to accommodate for choice number 2.

$(document).ready(function(){
$("select").change(function(){
    $(this).find("option:selected").each(function(){
        if($(this).attr("value")=="bfcn")

        {
            $(".discount-info").not(".bfcn").hide();
            $(".bfcn").show();
        } 

        else{
            $(".discount-info").hide();
        }
    });
})
.change();
});

HTML

<div> 
    <select>
        <option>Where are you travelling to?</option> 
        <option value="bfcn">Belfast</option> 
        <option value="bflp">Liverpool</option> 
    </select>
    <select class="peak"> 
        <option>What month are you travelling in?</option>
        <option value="offpeak">March, April, May, September</option>
        <option value="peak">July, August</option>
    </select>
</div>
<div class="bfcn discount-info"> 
    <div class="content"> PDF LINK HERE </div> 
</div>

No need to loop. Try this:

 <script>
 $(document).ready(function(){
    $('select').change(function(){
      if (($(this).val() == 'bfcn') && ($(this).siblings('select').val() == 'bfcn')){
        $('.bfcn').show();
      } else {
        $('.bfcn').hide();
      }
   });
 });
 </script>

This will only execute the show if the value of both selects are correct. You could even run a series of values in else if statements to display different things on different selections. If you have more than two selects and siblings doesn't work, you could use direct classes, but from your question this should work.

Here's my demo HTML:

 <select title="Select 1" id="select1">
    <option value="">Select an option</option>
    <option value="1">1</option>
    <option value="bfcn">bfcn</option>
 </select>
 <select title="Select 2" id="select2">
    <option value="">Select an option</option>
    <option value="3">3</option>
    <option value="bfcn">bfcn</option>
 </select>
 <p class="bfcn" style="display: none;">BFCN</p>

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