Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeroenvanrensen's avatar

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.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You need to use nextTick so that the reactive DOM changes resulting from show changing have been completed:

<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>

https://github.com/alpinejs/alpine#nexttick

5 likes

Please or to participate in this conversation.