Search code examples
c#asp.net-coreblazor.net-6.0blazor-webassembly

how can I move with the up and down keys in a list in a Blazor app


I made an autocomplete in a Blazor Wasm application with .net6 I can search and select with the mouse an item from the returned list. But in addition to using the mouse I would like to be able to use the keyboard.

Can this be done in a Blazor app without using JS?

I have started an implementation with the onkeydown to capture when they press the up and down keys and it works correctly.

But how can I do it to mark an item from the list?

I attach the code used so far:

 <div>
    <input @bind-value=selectedCustomerName @oninput=HandleInput onkeydown="@((KeyboardEventArgs e) => OnkeydownInput(e))" type="text" class="form-control" >
 </div>

    @if (ResultSearch is not null)
    {
        <ul class="options list-group">
            @if (ResultSearch.Any())
            {
                @foreach (var elementSearch in ResultSearch)
                {
                    <li class="option list" @onclick=@(() => SelectCustomer(elementSearch.Id))>
                        <span class="option-text">@elementSearch.Title</span>
                    </li>
                }
            }
            else
            {
                <li class="disabled option">No results</li>
            }
        </ul>
    } 

I attach an image of how it currently behaves using the mouse:

Autocomplete


Solution

  • You don't need to build your own. You can use a datalist attached to the input which supports keyboard support.

    Here's a quick demo:

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <div class="mb-3">
        <input type="text" class="form-control" list="countrylist" @bind=_country />
    </div>
    
    <datalist id="countrylist">
        @foreach (var country in _countries)
        {
            <option value="@country" />
        }
    </datalist>
    
    <div class="bg-dark text-white p-2 m-2">
        Selected value: @_country
    </div>
    
    @code {
        private List<string> _countries = new() { "Algeria", "Australia", "Austria", "Cook Islands" };
        private string? _country;
    }