Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

valentin_vranic's avatar

AlpineJs, bind selected text to input value

I want to bind the selected text instead of value to an input, how should I do that?

I've managed to bind them with x-model="selectedItem" but that is for value.

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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-data initializes the component state with selectedItem set to an empty string.
  • x-ref is used to create a reference to the select element, which can be accessed within Alpine.js expressions.
  • The @change directive listens for the change event on the select element. When the event is triggered, it updates selectedItem with the text of the currently selected option.
  • x-model binds the selectedItem to the value of the input field, which will automatically update when selectedItem changes.
  • The readonly attribute 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.

1 like

Please or to participate in this conversation.