What Is The Correct Way Of Getting The Value Of A Selected Drop Down Item Using JavaScript?

- 1 answer

I thought i knew this, and now I'm quite embarassed becuase I don't :-/

This JSFiddle demonstrates two ways of getting the value of a selected drop down item in JavaScript. Code reproduced here:

var obj = document.getElementById("test");
alert(obj.options[obj.selectedIndex].value);  //like this
alert(obj.value);  //or like this

Quirksmode suggests that some older broswers don't support the latter (, and value isn't a supported attribute in the HTML 4.01 spec.

So I wondered, which is the correct standarised way of doing this?




David is correct. If you want full compatibility you might want to use something like:

var options = document.getElementById('securityWalkInTime').children;
var value = [];
for (var i=0;i<options.length;i++) {
    var option = options[i];
    if (option.selected === true) {
        value.push(option.value ? option.value : option.text);

This will definitely work, however, for all practical cases I would use the latter of your example.