简体   繁体   中英

How to programmatically change the selected option in an html select tag

I have a select group in my html to select a price range with. The user can select a range, and then filter the results based on the selection. This works fine, however the user can also reset the results from a totally different place (a search box). I need to change the selection that is actually displayed in the select box so I can reset it to "show all" so that it doesn't look like it is still filtered by price range when the user has actually reset the results from the search box.

I'm able to change the actual value that is selected via the following:

document.getElementById("selectedPriceRange").setAttribute("value","0")

This does actually change the value held in the select box, but the box itself still displays whichever option was last selected.

How can I get the text that is shown in the select box to change without physically selecting another option?

Here's my select box:

<select #priceRangeOptions class="custom-select" id="inputGroupSelect01">
     <option *ngFor="let priceRange of priceRangeOptions; let i=index"
     id="selectedPriceRange" [value]="i">{{priceRange}}</option>
</select>

on select all you have to do is to set ngModel attribute and then you can change variable value to set value.

<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.';

or you can use javascript to do that

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

Don't use Javascript to query the DOM / set values

Also, from what you posted you don't need an index (although maybe you do)

Instead, you 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>

The [()] syntax denotes two way binding.

As a proof of concept, this typescript sets the model value:

export class AppComponent  {
  name = 'Angular';
  option: string;
  options: string[] = ['One', 'Another Choice','Wow, A Hotdog?'];

  setHotDog(){
    this.option = this.options[2];
  }
}

This would be the Angular way, and the correct approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM