Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlpineJs select box bind text not the value

Tags:

laravel

I want to bind the text of select option to the text of a span. I want to display the text of select box, not the value.

<div class="w-full flex" x-data="{category:0}">
        <div class="relative w-auto" >
                 <span x-text="category"></span>
        </div>
        <select id="category" class="cursor-pointer" x-ref="category" x-model="category">
             <option value=0 selected="selected">One</option>
             <option value=1>Two</option>
             <option value=2>Three</option>
       </select>
</div>

Now, when I select option, the span displays - 0, 1, 2.

I want to display "one", "two", "three" instead which are the text of select option.

How can I do this?

like image 708
GlobalKnowledge Avatar asked Mar 12 '26 21:03

GlobalKnowledge


1 Answers

all you need is to add a reference for your select after that you can access the options collection

and you can access your selected one by get it's index from selectedIndex property

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js" defer></script>
<div x-data="{category: 0}">
  <h1 x-text="$refs.categoryEL.options[$refs.categoryEL.selectedIndex].text"></h1>
  <select x-model="category" x-ref="categoryEL">
    <option value="0">one</option>
    <option value="1">two</option>
    <option value="2">three</option>
  </select>
</div>
like image 85
Joseph Avatar answered Mar 14 '26 12:03

Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!