Reputation: 53
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
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