blazorbootstrap icon indicating copy to clipboard operation
blazorbootstrap copied to clipboard

CurrencyInput: Focus is not working

Open joselitogatchalianalonzo opened this issue 6 months ago • 2 comments

Hi @gvreddy04 I want to set the focus on CurrencyInput I use for entering discount, but it does not work.

In my Razor file:

<CurrencyInput id="curDiscount" TValue="decimal" HideCurrencySymbol="true" MaximumFractionDigits="2" TextAlignment="Alignment.End" @bind-Value="_CommandTextInput.discount_amount" />

In my cs file inside OnAfterRenderAsync method:

_JSRuntime.InvokeVoidAsync("focusById", "curDiscount");

In my javascript file I have this function:

function focusById(elementId) {
    let element = document.getElementById(elementId);
    if (element)
        element.focus();
}

Please let me know what am I missing here.

Hi @joselitogatchalianalonzo

this does not work because all components within BlazorBootstrap generate a property id by default. So the provided id from you won't be applied to the element.

However there is a way to focus the input. You'll need to do it the same way as for normal input components from Microsoft.

Here is a short example for your use-case:

<CurrencyInput @ref="_input" TValue="decimal" HideCurrencySymbol="true" MaximumFractionDigits="2" TextAlignment="Alignment.End" @bind-Value="_CommandTextInput.discount_amount" />

@* just to trigger focus somehow *@
<Button Color="ButtonColor.Primary" @onclick="FocusAsync">Focus</Button>
@code {

    private CurrencyInput<decimal> _input = default!;
    private async Task FocusAsync()
    {
        await _input.ElementRef.FocusAsync();
    }

}

MarvinKlein1508 avatar Jan 26 '24 13:01 MarvinKlein1508

Thanks @MarvinKlein1508 I will try your suggestion.