To bind the selected text from a dropdown (select element) to an input field using Alpine.js, you can use the x-text directive on an element to display the text, and then use x-ref to reference the select element. Here's an example of how you can achieve this:
<div x-data="{ selectedItem: '' }">
<select x-ref="select" @change="selectedItem = $refs.select.options[$refs.select.selectedIndex].text">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<!-- Add more options here -->
</select>
<!-- This input will display the selected text -->
<input type="text" x-model="selectedItem" readonly />
<!-- This is just to show the selected text in a span for demonstration -->
<span x-text="selectedItem"></span>
</div>
In this example:
-
x-datainitializes the component state withselectedItemset to an empty string. -
x-refis used to create a reference to the select element, which can be accessed within Alpine.js expressions. - The
@changedirective listens for the change event on the select element. When the event is triggered, it updatesselectedItemwith the text of the currently selected option. -
x-modelbinds theselectedItemto the value of the input field, which will automatically update whenselectedItemchanges. - The
readonlyattribute on the input field is optional and is used to prevent the user from editing the text directly.
Remember that the input field is now displaying the text of the selected option, not the value. If you need to submit the value as part of a form, you will need to handle that separately.