[AlpineJs] How to set focus on an input element from an element outside the scope? Hi, I am using latest version of Alpine. I need to set focus on the input searchbox as soon as it become visible. Here is my code for reference.
<div x-data="{search: false}">
<button x-click="search = true">Click to open search box</button>
<div x-data="searchwidget" x-show="search">
<input type="search" x-model="term" x-ref="searchInput" />
</div>
</div>
Data handler for search input widget
document.addEventListener('alpine:init', () => {
Alpine.data('searchwidget', () => ({
term: "",
}));
});
I tried to put $refs.searchInput.focus() on button element, but its not working.
I'm not sure that it's possible to have an alpine object inside an alpine object.
I suggest you to try this.
<div x-data="{searchdiv}">
<button x-click="search = true">Click to open search box</button>
<div x-show="search">
<input type="search" x-model="term" x-ref="searchInput" />
</div>
</div>
...
document.addEventListener('alpine:init', () => {
Alpine.data('searchdiv', () => ({
term: "",
search: false,
}));
});
What error did you get? Can you show the code you actually tried with?
Did you try this?
<div x-data="{search: false}">
<button @click="search = true;$refs.searchInput.focus()">Click to open search box</button>
<div x-data="searchwidget" x-show="search">
<input type="search" x-model="term" x-ref="searchInput" />
</div>
</div>
What is this x-click you’re using? It looks like a morph between x-on:click and @click , but I don’t think it exists.
The following ought to work, as far as I can tell:
<div x-data="{search: false}">
<button x-on:click="search = true; $refs.searchInput.focus()">Click to open search box</button>
<div x-data="searchwidget" x-show="search">
<input type="search" x-model="term" x-ref="searchInput" />
</div>
</div>
@vincent15000 Yes, nested Alpine objects are possible, as of Alpine 3.
Edit: Seems Sinnbeck wrote the exact same thing while I was Googling to see if x-click was actually a thing.
Please sign in or create an account to participate in this conversation.