Search code examples
razorradio-buttonblazor

Uncheck radio button inside Razor Component


I'm creating radio buttons like this inside a Razor component:

@for (int i = 0; i < 4; i++)
{
    int answerIndex = i;
    <input type="radio" @onclick="(() => Answer(answerIndex))"/> @options[i]
    <br />
}

I would like for the button I clicked to get unchecked inside the Answer() function but I can't find a way to bind the checked property to a variable.

I have tried to do checked=@boolean but when I check it the boolean doesn't change nor does it get unchecked when I change the boolean.


Solution

  • Here's a demo page showing how to bind to a Radio buttons using the built in InputRadioGroup control. I've also switched to a foreach to avoid index problems.

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    <InputRadioGroup @bind-Value=_selectedCountry>
        @foreach (var country in _countries)
        {
            <div>
                <InputRadio Value="country" />
                @country
            </div>
        }
    </InputRadioGroup>
    
    <div class="m-2">
        <button class="btn btn-primary" @onclick=this.ClearValue>Clear</button>
    </div>
    
    <div class="bg-dark text-white m-2 p-2">
        <pre>Country : @(_selectedCountry ?? "Not Set")</pre>
    </div>
    @code {
        private string? _selectedCountry;
    
        public List<string> _countries = new()
        {
            "UK",
            "France",
            "Spain"
        };
    
        public void ClearValue()
            => _selectedCountry = null;
    }
    

    Or if you want to use objects:

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    <InputRadioGroup @bind-Value=_selectedCountryUid>
        @foreach(var country in _countries)
        {
            <div>
                <InputRadio Value="country.Uid" />
                @country.Name
            </div>
        }
    </InputRadioGroup>
    
    <div class="m-2">
        <button class="btn btn-primary" @onclick=this.ClearValue>Clear</button>
    </div>
    <div class="bg-dark text-white m-2 p-2">
        <pre>Country : @(_selectedCountry?.Name ?? "Not Selected")</pre>
    </div>
    @code {
        private Guid? _selectedCountryUid;
        private Country? _selectedCountry => _countries.FirstOrDefault(item => item.Uid.Equals(_selectedCountryUid));
    
        public List<Country> _countries = new()
        {
            new( Guid.NewGuid(), "UK"),
            new( Guid.NewGuid(), "France"),
            new( Guid.NewGuid(), "Spain")
        };
    
        public void ClearValue()
            => _selectedCountryUid = null;
    
        public record Country(Guid Uid, string Name); 
    }