Date: 2009mar27
Language: javaScript
Q. How can I get the value of an HTML <select> in javaScript?
A. Use this function:
function getSelectValue(objSelect) {
if (objSelect == null) return null;
if (objSelect.selectedIndex < 0) return null;
return objSelect.options[objSelect.selectedIndex].value;
}
It works in all browsers.
function exampleUse() {
const obj = document.getElementById('my-select');
const value = getSelectValue(obj);
alert('value of my-select=' + value);
}
// A generalized getValue() function...
function getValue(obj) {
let value;
if (obj == null) return null;
if (obj.options) {
value = setSelectValue(obj);
}
else {
value = obj.value;
}
return value;
}
With jQuery its the same as getting any other value:
const value = $('#my-select').val();