How to implement InputCheckbox OnChange Event?

104 Views Asked by At

I have a InputCheckbox in an EditForm. This is used in a Blazor Web Server application. I want to show and hide a text field based on the check box state. I am unable to get the event for ValueChanged to work correctly.

<EditForm id="formMember" Model="@member">
<InputCheckbox 
   id="Adegree12" 
   class="form-check-input" 
   Value="member.Adegree12" 
   ValueChanged="((bool Adegree) => ADegreeSelectionChanged(Adegree))" 
   ValueExpression="(() => member.Adegree12)" />
</EditForm>

I am using this code for the InputCheckbox. Without the "Value" attribute the functionality works fine. I can catch the changed value and show or hide the text field. But when I added the "Value" attribute, the checkbox stopped changing. I have added the "Value" attribute to use the same form for the Edit scenario.

Update: If I remove the Editform tag then the functionality works fine. But with the Editform tag, if the checkbox is clicked then it checks and unchecks instantly which wrong. Maybe I am not using the EditForm tag correctly?

1

There are 1 best solutions below

2
MrC aka Shaun Curtis On BEST ANSWER

Without seeing more of your code I can't answer based on your context. Instead I've constructed a simple Index to demonstrate how the binding works in principle. Note both types of binding work.

The simpler second version works because the compiled Razor code looks similar to the first example.

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<div class="row">
    <div class="col-6">
        <InputCheckbox class="form-check" Value="_hide1" ValueChanged="CheckBoxChanged" ValueExpression="() => _hide1" />
        <InputText hidden="@_hide1" class="form-control mb-3" @bind-Value="@_textValue1" />
    </div>
    <div class="col-6">
        <InputCheckbox class="form-check" @bind-Value="_hide2" />
        <InputText hidden="@_hide2" class="form-control mb-3" @bind-Value="@_textValue2" />
    </div>
</div>


@code{
    private string? _textValue1;
    private string? _textValue2;
    private bool _hide1;
    private bool _hide2;

    private void CheckBoxChanged(bool state)
    {
        _hide1 = state;
    }
}