Javascript 如何以编程方式更改html选择标记中的选定选项
我在html中有一个选择组来选择价格范围。用户可以选择一个范围,然后根据选择过滤结果。这很好,但是用户也可以从完全不同的位置(搜索框)重置结果。我需要更改实际显示在选择框中的选择,以便我可以将其重置为“全部显示”,这样,当用户实际重置搜索框中的结果时,它看起来不会仍然按照价格范围进行过滤 我可以通过以下方式更改所选的实际值:Javascript 如何以编程方式更改html选择标记中的选定选项,javascript,html,angular,html-select,Javascript,Html,Angular,Html Select,我在html中有一个选择组来选择价格范围。用户可以选择一个范围,然后根据选择过滤结果。这很好,但是用户也可以从完全不同的位置(搜索框)重置结果。我需要更改实际显示在选择框中的选择,以便我可以将其重置为“全部显示”,这样,当用户实际重置搜索框中的结果时,它看起来不会仍然按照价格范围进行过滤 我可以通过以下方式更改所选的实际值: document.getElementById("selectedPriceRange").setAttribute("value","0") 这实际上会更改“选择”框中
document.getElementById("selectedPriceRange").setAttribute("value","0")
这实际上会更改“选择”框中保留的值,但框本身仍会显示上次选择的选项
如何在不实际选择其他选项的情况下更改“选择”框中显示的文本
这是我的选择框:
<select #priceRangeOptions class="custom-select" id="inputGroupSelect01">
<option *ngFor="let priceRange of priceRangeOptions; let i=index"
id="selectedPriceRange" [value]="i">{{priceRange}}</option>
</select>
{{priceRange}}
在选择上,您所要做的就是设置ngModel属性,然后您可以将变量值更改为设置值
<select #priceRangeOptions [(ngModel)]="selectedValue" class="custom-select" id="inputGroupSelect01">
<option *ngFor="let priceRange of priceRangeOptions; let i=index"
id="selectedPriceRange" [value]="i">{{priceRange}}</option>
</select>
selectedValue = 'my selected value.';
不要使用Javascript查询DOM/设置值
此外,从你发布的内容来看,你不需要索引(尽管你可能需要索引)
相反,你
这将是一种有角度的方式,而且是正确的方法啊,确实非常有效!我只需要确保我使用了priceRange的索引值,而不是文本本身。非常感谢你!感谢您花时间回复!你是对的,一旦数据绑定正常工作,我就不需要索引了。我也不需要使用setAttributes,这是我出于绝望才添加的。我显然需要休息一下,吃点东西!:/NP,我对最初的答案有几个问题,希望它能更清楚地说明发生了什么。此外,很多刚接触Angular的人都希望使用类似JQuery的概念,而它真正做的只是使代码更容易破解,更难阅读。
document.getElementById('inputGroupSelect01').value = "value";
<select #priceRangeOptions class="custom-select" id="inputGroupSelect01" [(ngModel)]="option">
<option *ngFor="let option of options;"
id="selectedOption" [value]="option">{{option}}</option>
</select>
<button type="button" (click)="setHotDog()">Choose the hotdog</button>
export class AppComponent {
name = 'Angular';
option: string;
options: string[] = ['One', 'Another Choice','Wow, A Hotdog?'];
setHotDog(){
this.option = this.options[2];
}
}