Home > Enterprise >  Select option value doesnt reach if statement
Select option value doesnt reach if statement

Time:09-26

So I have question I have select option element:

<select id="item-types__profile" name="item_type_id">
   <option selected disabled style="display:none;" value="0"></option>
</select>

And on page load I am triyng to take selected value:

const typesSelect = document.getElementById('item-types__profile')

const test = typesSelect.options[typesSelect.selectedIndex].value;
console.log(test);
if (test === 0) {
    console.log('reached');
    document.querySelector('.item-fields').style.display = 'none';
}

To console it displays 0, but it doesn't reach if code and it doesn't print out console.log('reached'). I dont understand what could possibly be wrong here?

CodePudding user response:

Your condition tests for zero as a number or in Javascript that is know as an integar but the variable test is a string. Should be:

if (test === "0")

CodePudding user response:

Triple equality === is a strict comparison which means it also compares the type. Value from the select option is always a string, here it is "0" not 0. You should cast it to int before checking or use double equality ==.

CodePudding user response:

  • Use "==" not "==="

              const typesSelect = document.getElementById('item-types__profile')
    
              const test = typesSelect.options[typesSelect.selectedIndex].value;
              console.log(test);
              if (test == 0) { // here 
                  console.log('reached');
                  document.querySelector('.item-fields').style.display = 'none';
              }
    

CodePudding user response:

That would simply be because

Value : A String, representing the value of the text field

Simply put value returns a string not a integer so you can do :

if (test === "0") {
    console.log('reached');
    document.querySelector('.item-fields').style.display = 'none';
}

Alternately :

if (test == 0) {
    console.log('reached');
    document.querySelector('.item-fields').style.display = 'none';
}

The second one will work even though you get a string because we are not doing strict equal check (so 0 == '0') yields true while 0 === '0' yields false

  • Related