How to Create a Select Input in Alpine.js

I didn’t find a working example of how to create an HTML select input in Alpine.js online, so I’m presenting it here.

Select Input in Alpine.js

Basically, you create a “for” loop to generate the option values. One of the keys to making this work with stored values is to set the “:selected” property to true when the option is equal to the selection option value.

<div x-data="{ selected_option: '', 
 options: [ 
  'apples',
  'oranges', 
  'lemons'
]}">

 <label>My Select:
  <select x-model="selected_option">
   <option value=""> - Select - </option>
    <template x-for="option in options" :key="option">
     <option :value="option" x-text="option" :selected="option==selected_option"></option>
    </template>
   </select>
  </label>
</div>

Let me know how this worked for you in the comments! – Brian

Shares

Discover more from Web Developer Tips and Tricks

Subscribe to get the latest posts sent to your email.

Please Leave a Question or Comment

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments