最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论