Basics
Challenges
Classes
Debugging
Events
External Files
Flow Control
Forms
Functions
Html Elements
Installation
Interfaces
Keywords
Modules
Namespaces
Operators
Reference Files
String
Types
Getting the selected value is pretty easy. We use HTMLSelectElement.value
. This returns the value of the selected element.
See https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement.
To get the selected text from the selected item is a little more complex. We use the HTMLSelectElement.selectedOptions
property. This is a collection of selected items for the select
object. Since we know we only need the first one (rare that is set up to
select multiple), we can just target the zero-index selectedOption. See
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions
let valueDemo: HTMLElement = <HTMLElement>document.getElementById("demo-value");
let textDemo: HTMLElement = <HTMLElement>document.getElementById("demo-text");
let colorsList: HTMLSelectElement = <HTMLSelectElement>document.getElementById("ColorList");
valueDemo.innerHTML = `Your value is ${colorsList.value}`;
textDemo.innerHTML = `Your text is ${colorsList.selectedOptions[0].text}`;
Also - see the js version: change event.