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;
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"
You only need this line of code:
let value = (<HTMLSelectElement>document.getElementById('organization')).value;
This worked for me:
const target = e.target as HTMLSelectElement
console.log("%s is selected", (target[clickedIndex] as HTMLOptionElement).value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With