Ad
What Is The Correct Way Of Getting The Value Of A Selected Drop Down Item Using JavaScript?
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 (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?
Ad
Answer
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.
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad