Search code examples
javascripthtmlhtml-selectgetelementbyid

Proper way of getting boolean from option value for Javascript


This is my html:

<select id="popularCategorySelectID">
    <option id="1" value="false" selected="selected">No</option>
    <option id="2" value="true">Yes</option>
</select>   

And this is my javascript:

var popularCategorySelectElement = document.getElementById("popularCategorySelectID");
var popularCategorySelectElementValue = Boolean(popularCategorySelectElement.options[popularCategorySelectElement.selectedIndex].text);   

I want to get the Boolean value like true or false here in popularCategorySelectElementValue. With the above code I am always getting true. I have tried with [ngValue]="true" but the result is same true.

Thanks for your time!


Solution

  • let bool = document.querySelector('#popularCategorySelectID').value === "true" ? true : false
    

    Or even simply:

    // this will return true if the conditional is true 
    let bool = document.querySelector('#popularCategorySelectID').value === "true"
    

    You could get a boolean value as this.