简体   繁体   中英

How to use multiple conditional in jquery? Use both IF OR in jquery

I am trying IF with OR in jquery but only "Returns" is working. "In Process" is not working. Help needed.

$('.target').change(function() {
     if (($(this).find('option:selected').val() == 'Returns') || ($(this).find('option:selected').val() == 'In Process')) {
       $(".answer").show('slow');
     }
     else{
         $(".answer").hide('slow');
     }
   });

Use .val() to get the selected value of a select element. Have a look below, it's working perfectly fine

 $('.target').change(function() { if ($(this).val() == 'Returns' || $(this).val() == 'In Process') { $(".answer").show('slow'); } else{ $(".answer").hide('slow'); } }); 
 .answer{ height:50px; border:1px solid #333; display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="target"> <option value="">select</option> <option value="Returns">Returns</option> <option value="In Process">In Process</option> </select> <br> <div class="answer"></div> 

You can create an array of all correct values and if selected value exists in array, show answer else hide.

You can also use .toggle(expression) to control visibility.

Sample:

 $('.target').change(function() { var valid = ["Returns", "In Process"]; var value = $('option:selected', this).val().trim(); $(".answer").toggle(valid.indexOf(value) > -1) }); 
 .answer { height: 50px; border: 1px solid #333; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="target"> <option value="">select</option> <option value="Returns">Returns</option> <option value="In Process">In Process</option> </select> <br> <div class="answer">Answer</div> 

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