如何在TypeScript中获取DropDown的值

时间:2017-03-17 21:00:03

标签: javascript typescript

我的MVC视图中有一个下拉列表:

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

我尝试在类型脚本中获取下拉列表的值,如下所示:

 var e = (<HTMLInputElement>document.getElementById("organization")).value;

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

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

5 个答案:

答案 0 :(得分:6)

您需要使用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;

如果你想要任何回复,你需要定义值或文本

    '<select id="organization" value="ThisIsMyValue">This is my text</select>

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

答案 1 :(得分:2)

您只需要以下代码行:

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

答案 2 :(得分:1)

这对我有用:

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

答案 3 :(得分:0)

尝试一下

在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>

在TS中:

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

答案 4 :(得分:0)

我正在使用Angular 9,以下对我有用:

(作为HTMLSelectElement的document.getElementById(“ inputCategory”))。值

我的建议是将您的陈述重构为:

变量=(document.getElementById(“ organization”)as HTMLSelectElement).value

编码愉快!