2

I have 2 select list drop downs. Select list A has 10 values (int). If a certain selection is made aka: a specific value, then I want to Select list B to be hidden. Right now I have the hiding functionality, if I use multiple "||" or statements, but this is messy and no good practice. How do I check if a specific value is chosen without using a bunch of or statements?

Current Code (working but ugly):

$('#status').change(function(){
            let $appStatus = $('#status').val();

        if($appStatus == 400 || $appStatus == 606 || $appStatus == 620 || $appStatus == 700 || $appStatus == 1000 || $appStatus == 1020){
          console.log(true);
          $reasonNoHire.hide()
        }else{
          console.log(false);
          $reasonNoHire.show();
        }
      });

Other code I have tried by always returns false

            //Brought back depending on what the user chooses in Selectlist A
            let $appStatus = $('#status').val();
            let valArray = [400, 606, 620, 700, 1000, 1020];

            if(valArray.includes($appStatus)){
              console.log(true);
              $reasonNoHire.hide()
            }else{
              console.log(false);
              $reasonNoHire.show();
            }
          });

CodeConnoisseur
  • 1,452
  • 4
  • 21
  • 49
  • 1
    Why would the 2nd chunk return false? Can you `console.log($appStatus);` and see why? – TRose Oct 08 '19 at 19:50
  • Where do you want me to console.log it? – CodeConnoisseur Oct 08 '19 at 19:51
  • Yeah, the code looks correct. Good job being on the right track. Log $appStatus right after you declare it. – Tanner Oct 08 '19 at 19:51
  • 2
    `$appStatus` would be a string and you have an array of numbers. Either convert `$appStatus` to a number or make your array only have strings. – VLAZ Oct 08 '19 at 19:52
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Heretic Monkey Oct 08 '19 at 19:55

2 Answers2

3

The problem is that $appStatus is a string and not a number. This happens to pass in your first example because you are using == instead of ===. Array.prototype.includes returns false because [400].includes('400') is comparing a string to a number.

KevBot
  • 17,900
  • 5
  • 50
  • 68
1

$('#status').val() returns a string but you are comparing it against numbers. You are using loose equality in the first snippet. So, it works. But, includes uses Same-value-zero algorithm to compare (Almost equal to Strict Equality). So, change the array to an array of strings or convert the value to a number before checking includes

adiga
  • 34,372
  • 9
  • 61
  • 83