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 s开发者_如何学Come older broswers don't support the latter (http://www.quirksmode.org/js/forms.html), 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?
Anyone?
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.
Both are standard. Use the version with better browser support.
value isn't a supported attribute in the HTML 4.01 spec
This is DOM, not HTML.
精彩评论