Jeroen van Rensen
Jeroen van Rensen

Reputation: 53

Alpine.js - Show an input field and add focus to it at the same time

I have a button, and when a user clicks it, an input element should be shown and it should have focus.

I tried this:

<div x-data="{ show: false }">

    <input x-show="show" type="text" id="input" x-ref="input" />

    <button @click="show = !show; $refs.input.focus();">Button</button>

</div>

But it does not work.

Upvotes: 4

Views: 8118

Answers (1)

Craig E
Craig E

Reputation: 863

To put focus on the input immediately after showing it, you'll need to use Alpine's $nextTick function. Try this slightly altered version of your code:

<div x-data="{ show: false }">

    <input x-show="show" type="text" id="input" x-ref="input" />

    <button @click="show = !show; $nextTick(() => { $refs.input.focus(); });">Button</button>

</div>

Here's some more info about $nextTick: https://github.com/alpinejs/alpine#nexttick

Upvotes: 16

Related Questions