Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 416
nakisa Avatar asked Mar 17 '17 21:03

nakisa


3 Answers

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"

like image 184
ctay Avatar answered Oct 24 '22 08:10

ctay


You only need this line of code:

let value = (<HTMLSelectElement>document.getElementById('organization')).value;
like image 22
Carlos Silva Avatar answered Oct 24 '22 08:10

Carlos Silva


This worked for me:

const target = e.target as HTMLSelectElement
console.log("%s is selected", (target[clickedIndex] as HTMLOptionElement).value)
like image 31
Chris Avatar answered Oct 24 '22 07:10

Chris