vikramlearning / blazorbootstrap

An Enterprise-class Blazor Bootstrap Component library built on the Blazor and Bootstrap CSS frameworks.
https://docs.blazorbootstrap.com/
Apache License 2.0
670 stars 32 forks source link

CurrencyInput: Focus is not working #474

Open joselitogatchalianalonzo opened 9 months ago

joselitogatchalianalonzo commented 9 months ago

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.

MarvinKlein1508 commented 7 months ago

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();
    }

}
joselitogatchalianalonzo commented 7 months ago

Thanks @MarvinKlein1508 I will try your suggestion.