Home > Back-end >  Conditionally hide text fields in Blazor
Conditionally hide text fields in Blazor

Time:10-21

I have a dropdown list with options '1' and '2' and text fields with the same names. My goal is that when I select option '1' from the list, only the text field named '1' should appear. When I select '2', the text field 2 should appear. Here is my code:

<InputSelect id="value" DisplayName="value" @bind-Value="@selectValue"
                style="width: 85px; margin-left: 10px; margin-top: 15px" onchange="@Show">
                <option value="select">Select</option>
                <option value="one">1</option>
                <option value="two">2</option>
            </InputSelect>

            <div hidden="isShow"  style="margin-left: 9px;">
                <label for="One">1</label>
                <InputNumber id="one" @bind-Value="commands.One" style="width: 80px;" />
            </div>

             
            <div hidden="isShow" >
                <label for="Two">2</label>
                <InputText id="two" @bind-Value="commands.Two" style="width: 150px;" />
            </div>

@code {
        
    private bool IsShow { get; set; } = false;
            
    private void Show()
            {
                IsShow = !IsShow;
                Console.WriteLine(selectValue);
            }
        
        }
    
    private string selectValue { get; set;} = "select";

I have tried to make a function that would make them disappear but I've not succeeded. What am I doing wrong here?

CodePudding user response:

You're trying to use an attribute (hidden) with a value from your code, but you're not referencing the field value. You would need to use:

<div hidden="@IsShow" >

That's not really the best way to do this, though, because what happens if the user selects the "Select" option or you need to add more than two options? Here's another approach you could use:

<div hidden="@(selectValue == "one")" >

Here's a different approach that won't even emit the div if its corresponding value is not selected:

<InputSelect id="value" 
             DisplayName="value" 
             @bind-Value="@selectValue"
             style="width: 85px; margin-left: 10px; margin-top: 15px">
    <option value="select">Select</option>
        <option value="one">1</option>
        <option value="two">2</option>
    </InputSelect>

    @if (selectValue == "one")
    {
        <div lass="col-2" style="margin-left: 9px;">
            <label for="One">1</label>
            <InputNumber id="one"
                         @bind-Value="commands.One"
                         style="width: 80px;" />
        </div>
    }
    
    @if (selectValue == "two")
    {     
        <div >
            <label for="Two">2</label>
            <InputText id="two"
                       @bind-Value="commands.Two"
                       style="width: 150px;" />
        </div>
    }
  • Related