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
Add a ment  | 

1 Answer 1

Reset to default 16

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./alpinejs/alpine#nexttick

本文标签: javascriptAlpinejsShow an input field and add focus to it at the same timeStack Overflow