Search code examples
javascripthtmlangularhtml-select

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>

Solution

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