gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'text' of undefined for getting selected value in java script

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:34 24 4
gpt4 key购买 nike

我正在尝试从下拉值中获取选定的值,以提醒它正在显示

Uncaught TypeError: Cannot read property 'text' of undefined

谁能帮帮我?

var selectedObj = document.getElementById('selectedOption');

alert("selectedObj--->"+selectedObj);

var selectedOptionText = selectedObj.options[selectedObj.selectedIndex].text;

最佳答案

selectedIndex

Technical Details

Return Value: A Number, representing the index ofthe selected option in the drop-down list. The index starts at 0. Ifno option is selected, the value returned is -1

因此,如果没有选择任何选项,您最终会得到 selectedObj.options[-1],它将始终是 undefined...

所以你可以这样做:

var selectedOptionText = selectedObj.selectedIndex > -1 ? selectedObj.options[selectedObj.selectedIndex].text : null;

如果您希望 selectedOptionText 在未选择任何选项时为 null。

或者

var selectedIndex = selectedObj.selectedIndex;
if (selectedIndex === -1) selectedIndex = 0;
var selectedOptionText = selectedObj.options[selectedIndex].text;

如果您希望selectedOptionText在没有选择的情况下等于选择的第一个选项。

关于javascript - 未捕获的类型错误 : Cannot read property 'text' of undefined for getting selected value in java script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32758533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com