TransWikia.com

Proper way of getting boolean from option value for Javascript

Stack Overflow Asked by Avow Studio on November 20, 2021

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!

2 Answers

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.

Answered by Karan Kumar on November 20, 2021

You can simply do this :

document.getElementById("popularCategorySelectID").value

Answered by Alexandre Elshobokshy on November 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP