【问题标题】:How to programmatically change the selected option in an html select tag如何以编程方式更改 html 选择标记中的选定选项
【发布时间】:2019-07-02 23:17:17
【问题描述】:

我的 html 中有一个选择组来选择价格范围。用户可以选择一个范围,然后根据选择过滤结果。这很好用,但是用户也可以从完全不同的地方(搜索框)重置结果。我需要更改实际显示在选择框中的选择,以便我可以将其重置为“全部显示”,这样当用户实际重置搜索结果时,它看起来不会仍然按价格范围过滤盒子。

我可以通过以下方式更改选择的实际值:

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>

【问题讨论】:

    标签: javascript html angular html-select


    【解决方案1】:

    不要使用 Javascript 来查询 DOM/设置值

    此外,根据您发布的内容,您不需要索引(尽管您可能需要)

    相反,你can do this:

    <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];
      }
    }
    

    这将是 Angular 的方式,也是正确的方式

    【讨论】:

    • 感谢您抽出宝贵时间回复!你是对的,一旦我让数据绑定正常工作,我就不需要索引了。我也不需要使用 setAttributes,我只是出于绝望才添加的。我显然需要休息一下,吃点东西! ://
    • NP,我对原始答案有几个问题,希望它更清楚发生了什么。此外,很多刚接触 Angular 的人都希望使用类似 JQuery 的概念,而实际上它所做的只是让代码更容易破解和阅读。
    【解决方案2】:

    选择你所要做的就是设置 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来做到这一点

    document.getElementById('inputGroupSelect01').value = "value";
    

    【讨论】:

    • 啊,效果很好!我只需要确保我使用的是 priceRange 的索引值而不是文本本身。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多