admin管理员组文章数量:1243088
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.
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.
Share Improve this question asked May 11, 2021 at 8:29 Jeroen van RensenJeroen van Rensen 531 gold badge5 silver badges12 bronze badges 3- Are you sure alpine.js is being loaded correctly ? Because I've copied / pasted your code in a fiddle with alpine.js and it is working fine – Cedric Cholley Commented May 11, 2021 at 13:12
- Yes I am. You can check out this editor: w3schools./code/tryit.asp?filename=GQEY8EWSLJHB When I click the button, the input should show and have focus – Jeroen van Rensen Commented May 11, 2021 at 16:23
-
Sorry I didn't understand that the not-working part was the focus. Craig E's answer below is the correct one (you may use
setTimeout
as well) – Cedric Cholley Commented May 12, 2021 at 19:21
1 Answer
Reset to default 16To 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./alpinejs/alpine#nexttick
本文标签: javascriptAlpinejsShow an input field and add focus to it at the same timeStack Overflow
版权声明:本文标题:javascript - Alpine.js - Show an input field and add focus to it at the same time - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740143636a2231369.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论