Home > OS >  How to check for multiple values in a jquery IF statement
How to check for multiple values in a jquery IF statement

Time:05-31

I have the below code which shows/hides a div based on an option in a dropdown, however it only toggles when a user selects 1. There are a few items in my dropdown that I'd like to show the DIV for. For example, let's say I have values 1 through 8 in my dropdown, and I want to show a DIV when a user has selected 4, 6, and 7. I don't want the DIV to toggle off and hide if a user changes selection from 4 to 6 either.

    $(document).ready(function(){
    $('#TypeofAction').on('change', function() {
      if ( this.value == '1') 
      //.....................^.......
      {
        $("#business").show();
      }
      else
      {
        $("#business").hide();
      }
    });
        
});

CodePudding user response:

Use an array to store the "On" values and check that using the boolean display variable in jquery's toggle:

$(document).ready(function() {
  $('#TypeofAction').on('change', function() {
    let onVals = ["4", "6", "7"];
    $("#business").toggle(onVals.includes(this.value));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="TypeofAction">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<div id="business">It's busness time!</div>

CodePudding user response:

You can use switch() or you could write the if/else in completely different way.. but here it is:

switch (this.value) {
  case '1':
  case '4':
  case '6':
  case '7':
    $("#business").show();
    break;
  case '2':
    $("#business").hide();
    break;
  case '3':
    console.log('do something else..');
    break;
  default:
    console.log('Invalid selection..');
}

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch


You can also go the route of using multiple if conditions:

if ( this.value == 1 || this.value == 4 || this.value == 6 || this.value == 7 ) {
...
}elseif( this.value == 2 || this.value == 3 ){
...
}else{
...
}

Or you could add the valid values in an array, and check with indexOf()

if ([1,4,6,7].indexOf(this.value) > -1){
...
}

or replace indexOf() with includes():

if ([1,4,6,7].includes(this.value)){
...
}
  • Related