In blazor component, focus in input text, how to make tab key to move focus to options drop-down?

4.8k Views Asked by At

I type something in the input field, the options narrowed. Then, by pressing tab the focus skips options drop-down. I want it to jump to options list. I have a sample below. Can it be done by html attributes only? if no, how can i do it in blazor?

I know up & down keys do that. But I feel it's faster and more intuitive for tab key.

<input type="text" @bind="@newStudyCode" list="studies" autocomplete="on" placeholder="Search ..." />
<datalist id="studies">
        @if (Studies != null)
        {
            @foreach (var study in Studies)
            {
                <option value="@study.Code">@study.Code - @study.Title</option>
            }
        }
    </datalist>

the compiled html is looking like this

<form>
  <input type="text" list="browsers" autocomplete="on" placeholder="Search ...">
  <datalist id="browsers">
            <option value="Firefox" tabindex="1">
                Firefox
            </option>
            <option value="Internet" tabindex="2">
                Internet
            </option>
            <option value="Chrome" tabindex="3">
                Chrome
            </option>
            <option value="Safari" tabindex="4">
                Safari
            </option>
  </datalist>
  <button type="submit">Push me</button>
</form> 

2

There are 2 best solutions below

3
Kyle On

This can be done just using regular html tabindex attribute. Nothing special for blazor needed.

Example:

<a href="https://www.w3schools.com/" tabindex="2">W3Schools</a>
<a href="http://www.google.com/" tabindex="1">Google</a>
<a href="http://www.microsoft.com/" tabindex="3">Microsoft</a>

See here: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex

1
Matt On

As Kyle just said, you just need tabindex

 <input type="text" @bind="@newStudyCode" list="studies" autocomplete="on" placeholder="Search ..." /> 
    <datalist id="studies"> 
       @if (Studies != null) 
          { 
            var i =1;
            @foreach (var study in Studies) 
               { 
                  <option value="@study.Code" tabindex="@i">
                    @study.Code - @study.Title
                  </option
                  i++;
               }
            } 
      </datalist>