How get the Value of DropDown in TypeScript
I have a drop down list in my MVC view as :
<select id="organization" class="create-user-select-half"></select>
I try to get the value of dropdown in Type Script like this:
var e = (<HTMLInputElement>document.getElementById("organization")).value;
but it return empty, this is how I get the textbox value and it is working. Also I tired this code but options and selectedIndex are undefined.
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
Solution 1:
You need to use the HTMLSelectElement instead, but this can be tricky
var e = (document.getElementById("organization")) as HTMLSelectElement;
var sel = e.selectedIndex;
var opt = e.options[sel];
var CurValue = (<HTMLSelectElement>opt).value;
var CurText = (<HTMLSelectElement>opt).text;
You will need to define the value or text though if you want anything back
'<select id="organization" value="ThisIsMyValue">This is my text</select>
Output
CurValue = "ThisIsMyValue"
CurText = "This is my text"
Solution 2:
You only need this line of code:
let value = (<HTMLSelectElement>document.getElementById('organization')).value;
Solution 3:
This worked for me:
const target = e.target as HTMLSelectElement
console.log("%s is selected", (target[clickedIndex] as HTMLOptionElement).value)
Solution 4:
I'm using Angular 9 and the following worked for me:
(document.getElementById("inputCategory") as HTMLSelectElement).value
My suggestion is for you to refactor your statement to:
var e = (document.getElementById("organization") as HTMLSelectElement).value
Happy coding!