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?
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")
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 ==.
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';
}