Search code examples
c#razorblazorblazor-server-sideinput-field

How can I empty a text input field via markup code (when I click the Input-field) in my Razor page of my Blazor Server app?


I have a text input field in my razor page, where the client should enter an IP address. The initial text of the input field is "Enter IP adress here". As soon as the client clicks into the input field, I want that the "Enter IP adress here" text dissapears, so that the client can write the IP address. I have tried following code with "bind", but didn't work. As you in the code, I have tried both with onclick and onselect events of the input field to delete the text.

@page "/connect2"

<h>How do you want to select your MAE?</h>
<br>
<select @onchange="func_ST">
<option value="">-- Select MAE from List --</option>
<option value="">-- Enter IP address --</option>
</select>

@if (TagService.selectedString_ST == "-- Enter IP address --")
{
<input type="text" @bind="@TagService.IP_Manuel"  onclick="func_IP_Set" onselect="func_IP_Set" >
}


@code {
async void func_ST(Microsoft.AspNetCore.Components.ChangeEventArgs e)
{
    if (TagService.selectedString_ST == "-- Enter IP address --")
    {
        TagService.IP_Manuel = "Enter IP";
        StateHasChanged();
    }

}
async void func_IP_Set()
{
    if(TagService.IP_Manuel=="Enter IP")
    {
        TagService.IP_Manuel = "";
        StateHasChanged();
    }
}
}

Solution

  • For simplicity, you might consider the placeholder attribute instead. The placeholder text will appear when no value is set in the input and disappear once a value is entered.

    <input type="text" placeholder="-- Enter IP address --">