简体   繁体   中英

Uncaught TypeError: Cannot read property 'text' of undefined for getting selected value in java script

I am trying to get the selected value from the drop down value, in alert it is showing

Uncaught TypeError: Cannot read property 'text' of undefined

can anyone help me?

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 of the selected option in the drop-down list. The index starts at 0. If no option is selected, the value returned is -1

So if no option is selected, you end up with selectedObj.options[-1] , which will always be undefined ...

So you could do:

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

If you want selectedOptionText to be null if no option is selected.

Or

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

If you want selectedOptionText to be equal to the first option of the select if no option is selected.

What do you expect 'selectedObj' to be? A HTML option element or a select element? This is ambiguous in the code...

selectedObj.options

implies it's the select element as does

selectedObj.selectedIndex

but

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

implies this is a HTML Option element.

You need to inspect:

console.log(selectedObj.tagName)

Note using console.log() is an easier debugging option than alert().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM