Skip to content

Instantly share code, notes, and snippets.

@tiendq
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tiendq/a35e873418ba8d96e475 to your computer and use it in GitHub Desktop.
Save tiendq/a35e873418ba8d96e475 to your computer and use it in GitHub Desktop.
Get selected value/text
// I saw a sample code like this, but don't do it.
function() {
var selectId = "mySelectList";
try {
var options = document.getElementById(selectId).options;
for (var i = 0;i < options.length;i++){
if(options[i].selected) {
return options[i].value;
}
}
} catch(e) {}
return "";
}
// The much better way is using querySelector.
var selectItem = document.querySelector("#" + selectId);
return selectItem.options[selectItem.selectedIndex].value;
// And, finally, even better than better.
return document.getElementById(selectId).value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment