I am using @bind-value to bind the selected value of a select element to a variable in Blazor. It works fine, if I physically click the drop down and select a value. However, if I select a value in the drop down through Javascript, Blazor doesn't seem to detect the change. I wrote a very simple program to demonstrate.
Here is my component .cshtml code:
@page "/"
@inject IJSRuntime JsRuntime
<select id="my-select-box" @bind-value="MyValue" @bind-value:event="onchange">
<option value="0">-- Select Something --</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<br />
@if (MyValue == "0") {
<div>Select an option</div>
} else {
<div>You chose @MyValue</div>
}
<div style="margin-top: 20px">
<button @onclick="@(() => SelectOptionThroughJs("1"))">Select Option 1</button>
<button @onclick="@(() => SelectOptionThroughJs("2"))">Select Option 2</button>
<button @onclick="@(() => SelectOptionThroughJs("3"))">Select Option 3</button>
</div>
@code {
public string MyValue {get;set;} = "0";
public async Task SelectOptionThroughJs(string option)
{
await JsRuntime.InvokeVoidAsync("helperFunctions.selectOption", option);
}
}
And here is my javascript code:
window.helperFunctions = {
selectOption: function(op) {
var selectBoxElement = document.getElementById("my-select-box");
selectBoxElement.value = op;
}
}
I also created a fiddle to demonstrate.
If you physically select an item from the drop down, you'll see it works just fine. However, if you click one of the 3 buttons, you'll see the value does change in the drop down, but Blazor does not seem to realize the value changed.
How can I fix this issue?