I try to set a Blazor InputCheckbox via javascript and expect that the Databinding is executed and the value is written to the Model. But to no avail. What am I doing wrong?
// blazor
<EditForm Model="@Model" OnValidSubmit="@HandleValidSubmit" >
<InputCheckbox @bind-Value="Model.Checked" class="tripCheckbox" />
</EditForm>
// javascript
const tripCheckBox = container.querySelector('.tripCheckbox');
if (tripCheckBox.checked === false) {
tripCheckBox.setAttribute('checked', 'checked');
tripCheckBox.checked = true;
} else {
tripCheckBox.removeAttribute('checked');
tripCheckBox.checked = false;
}
I think that you want to execute your js in some event:
<InputCheckbox @bind-Value="Model.Checked" class="tripCheckbox" @onclick=OnMyCheckboxClick />
// Code behind
[Inject]
private IJRunTime Js {get; set;}
private async task OnMyCheckboxClick() {
Js.InvokeVoidAsync("YourJSMethod");
}
The problem in changing the value with JS is the Blazor events don't get called. You have to invoke the DOM events yourself.
Here's a demo page and code, using most of your code:
My JS function loaded in _layout.cshtml.
<script>
window.SetMyCheckBox = function()
{
const tripCheckBox = document.getElementById('tripCheckbox');
if (tripCheckBox.checked === false) {
tripCheckBox.setAttribute('checked', 'checked');
tripCheckBox.checked = true;
var event = new Event('change');
tripCheckBox.dispatchEvent(event);
} else {
tripCheckBox.removeAttribute('checked');
tripCheckBox.checked = false;
var event = new Event('change');
tripCheckBox.dispatchEvent(event);
}
}
</script>
And this is a test page:
@page "/"
@inject IJSRuntime JS
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
<EditForm Model="@model">
<InputCheckbox @bind-Value="model.Checked" id="tripCheckbox" />
</EditForm>
<div class="m-2">
Checked: @model.Checked
</div>
<div class="m-2">
<button class="btn btn-primary" @onclick="Clicked"> Change </button>
</div>
@code {
private Model model = new Model();
class Model
{
public bool Checked { get; set; }
}
private async Task Clicked()
{
await JS.InvokeVoidAsync("SetMyCheckBox");
}
}