Focus an input with Alpine.js

To focus an input element with Alpine.js, we can use the standalone x-init directive.

<input x-init="$el.focus()" autofocus type="number">

 

However, if your input element is hidden and becomes visible after an event(e.g: click, change, ..) you'll need to use Alpine's $nextTick function.

<div
  x-data="{
    addNew: false,
    focus: function() {
        const textInput = this.$refs.myFocusedInputInput;
        textInput.focus();
        textInput.select();
      }
    }"
>

  <div x-show="!addNew">
    <strong x-on:click="addNew = !addNew; $nextTick(() => focus())">Add New</strong>
  </div>

  <div x-show="addNew" x-cloak>
    <input type="number" x-ref="myFocusedInputInput">
  </div>
</div>

 

********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************