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>

2 Answers

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

2

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";
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest