html - Proper way of getting boolean from option value for Javascript - Stack Overflow

This is my html:<select id="popularCategorySelectID"><option id="1" value

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!

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!

Share Improve this question edited Jul 22, 2020 at 7:56 Andrew 3833 silver badges15 bronze badges asked Jul 22, 2020 at 7:35 Avow StudioAvow Studio 873 silver badges8 bronze badges 3
  • Well, you're selecting the text inside each option. So you're selecting "No" or "Yes" which have no direct relation to a boolean value. Also, any non-empty string using Boolean() will return true. – Nathan Champion Commented Jul 22, 2020 at 7:39
  • You could make a function which checks the value Yes or No and returns a boolean. – Karan Kumar Commented Jul 22, 2020 at 7:40
  • I think you can find the answer in here. – Sett Paing Commented Jul 22, 2020 at 7:41
Add a ment  | 

2 Answers 2

Reset to default 4
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.

You can simply do this :

document.getElementById("popularCategorySelectID").value

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745335714a4623093.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信