Home > Back-end >  How to add an on change event to an inputRadio?
How to add an on change event to an inputRadio?

Time:10-11

Does anybody know how to add an on change event to an inputRadio?

I know you can do the following

<input type="radio" @onchange="ChangeFunction"/>

and this will hit the ChangeFunction() however if I do the following

<InputRadioGroup @bind-Value="@i.LeaveRequest.DayTime">
    <label>Full Day</label>
    <InputRadio Value="@FullDay" class="checkbox-P" @onchange="ChangeFunction"/>
</InputRadioGroup>

it never hits the function.

I've also tried adding @onchange="ChangeFunction" to the InputRadioGroup line however neither seem to hit the function.

Anyone got any idea how to do this?

CodePudding user response:

You can create normal radio buttons:

@foreach (var item in new string[] {"AspNetCore","AspNet","SomeJsThingWhatever"})
 {
  <div>
      <input type="radio" name="technology" id="@item" value="@item" 
         @onchange="RadioSelection" 
         checked=@(RadioValue.Equals(item,StringComparison.OrdinalIgnoreCase)) 
         />
      <label for="@item">@item</label>
   </div>
 }
<div>
   <label>Selected Value is @RadioValue</label>
</div>
 @functions
 {
   string RadioValue = "aspnetcore";
    void RadioSelection(ChangeEventArgs args)
    {
      RadioValue = args.Value.ToString();
    }
  }

Source

CodePudding user response:

Blazor page

<EditForm Model="Items">
<InputRadioGroup ValueChanged="@((e) => OnRadiochange(e))" TValue="string" ValueExpression="() => SelectedValue">
    @foreach (var item in Items)
    {
        bool Checked= false;
        if (SelectedValue.Equals(item, StringComparison.OrdinalIgnoreCase))
        {
            Checked = true;
        }
    <div class="form-check">
        <InputRadio Value="@item" class="form-check-input" checked=@Checked />
        @item <br />
    </div>
    }
</InputRadioGroup>

Code behind

public string SelectedValue { get; set; } = "AspNetCore";
public List<string> Items { get; set; } = new List<string> { "AspNetCore", "AspNet", "SomeJsThingWhatever" };

    private void OnRadiochange(object sender)
    {
        SelectedValue = (string)sender;
        StateHasChanged();
    }
  • Related