如何在 TypeScript 中获取 DropDown 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42867007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:21:39  来源:igfitidea点击:

How get the Value of DropDown in TypeScript

javascripttypescript

提问by nakisa

I have a drop down list in my MVC view as :

我的 MVC 视图中有一个下拉列表,如下所示:

 <select id="organization" class="create-user-select-half"></select>

I try to get the value of dropdown in Type Script like this:

我尝试在 Type Script 中获取 dropdown 的值,如下所示:

 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.

但它返回空,这就是我获取文本框值的方式并且它正在工作。我也厌倦了这段代码,但 options 和 selectedIndex 未定义。

 var value = e.options[e.selectedIndex].value;
 var text = e.options[e.selectedIndex].text;

回答by ctay

You need to use the HTMLSelectElement instead, but this can be tricky

您需要改用 HTMLSelectElement,但这可能很棘手

    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"

输出
CurValue=“ThisIsMyValue”
CurText=“这是我的文字”

回答by Carlos Silva

You only need this line of code:

你只需要这行代码:

let value = (<HTMLSelectElement>document.getElementById('organization')).value;

回答by Chris

This worked for me:

这对我有用:

const target = e.target as HTMLSelectElement
console.log("%s is selected", (target[clickedIndex] as HTMLOptionElement).value)

回答by Snow Bases

Try this

试试这个

In HTML:

在 HTML 中:

<select #organization (change)="selectOrganization(organization.value)" class="create-user-select-half">
    <option *ngFor="let o of organizationList"
        [value]="organization.id" 
        [selected]="organizationFromDB == o.organization_name">
        {{ o.organization_name }}
    </option>
</select>

In TS:

在 TS 中:

selectOrganization(id) {
    console.log('id', id);
}