Ger
Ger

Reputation: 21

How to display select options on alpinejs

So Im working with alpinejs and I want to make a "select" where the options come from an alpinejs x-data that returns an array of nodes. I know how to do it in vanilla js where you just need to create a loop and then append those elements to the parent element. But have no clue of how to do it in alpine since Ive tried different options and none are working.

<div x-data="{ options: $el.querySelectorAll('.m-tab__title') }">
 <select class="w-full md:hidden">
        <template x-for="option in options">
            <option x-html="option"></option>
        </template>
 </select>...

That just doesnt display any content in the select but [object HTMLDivElement].

 <div x-data="{ options: $el.querySelectorAll('.m-tab__title') }">
     <select class="w-full md:hidden">
            <template x-for="option in options">
                <option x-text="option.innerText"></option>
            </template>
     </select>...

While that displays just the inner Text of each option but not even inside a proper select.

Any way I can display each option as a select option?

Thanks!

Upvotes: 2

Views: 13592

Answers (1)

Out of Orbit
Out of Orbit

Reputation: 563

Are you sure your options array contain valid data?

If unsure you could always add x-init="console.log(options);" to your "x-data div"

I made a quick working example here: https://codepen.io/outoforbit/pen/JjWaJKN

<div x-data="{ selectedOption: 'option1', 
         options: [ 
            'option1',
            'option2', 
            'option3'
         ]}">
<div class="w-80 flex pr-3">
    <p class="w-1/2">Select option:</p>
    <div class="w-1/2 inline-block relative">
        <select name="my_option" x-model="selectedOption" class="">
            <template x-for="option in options" :key="option">
                <option :value="option" x-text="option"></option>
            </template>
        </select>
    </div>
</div>
Select option:

Upvotes: 1

Related Questions