Change value of select option by clicking anchor tag with Alpine.js

1.8k views Asked by At

I'm using x-data to dynamically build my HTML. I have two anchor tags which act as tab buttons to'x-show' a paragraph depending on which link is clicked. I also would like that anchor tag to select an option on the form's select element. It kind of works when you starts clicking on the buttons but initially the select options are empty?

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>
<div x-data="{activeTab : window.location.hash ? window.location.hash.substring(1) : 0, lessons:[{id:0,room:'online',description:'Online description'},{id:1,room:'in class',description:'in class description'}]}" class="w-full">
  <nav class="w-full flex flex-no-wrap justify-between mb-8">
    <template x-for="lesson in lessons">
      <a href="#" @click.prevent="activeTab = lesson.id; window.location.hash = 0; select = lesson.room" class="focus:outline-none focus:text-teal-800 hover:text-teal-800 meta bold py-1 uppercase mr-1 flex items-center justify-between text-lg w-1/2 border-b-4 focus:border-teal-800 hover:border-teal-800 border-teal-600 tracking-widest text-teal-600"><span x-text="lesson.room"></span><svg class="w-6 h-6" width="6" height="6" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg">
          <path d="m8.5.5-4 4-4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" transform="translate(6 8)" /></svg></a>
    </template>
  </nav>
  <template x-for="lesson in lessons">
    <div x-show="activeTab === lesson.id">
      <p x-text="lesson.description" class="text-gray-800 mb-6">Online classes are streaemed to your device. You can atned a yoga class wherever there is a why-fi</p>
    </div>
  </template>

  <form action="">
    <fieldset class="border p-4">
      <legend class="text-center text-xs uppercase tracking-widest text-orange-800 px-2">choose a classroom</legend>
      <select class="uppercase text-lg tracking-widest text-teal-800 w-full border border-teal-800 px-5 py-4 focus:outline-none focus:border-shadow rounded" name="" id="" x-model="select">
        <template x-for="lesson in lessons">
          <option x-text="lesson.room"></option>
        </template>
      </select>
    </fieldset>
  </form>
</div>

2

There are 2 answers

0
James On

I added:

x-init="select = lessons[0].room"

to the parent of the component which set the select to the initial value

0
John Magnolia On

A better way would be to add this onto the select

<select x-model="foo" x-init="foo = $el.options[$el.selectedIndex || 0].value">