Alpine.js Playground
Examples Newsletter

Bound "select" and access selection data example

Bound "select" and access selection data

<div 
  x-data="page()" class="flex flex-col"
>
  <h3 class="text-xl font-semibold text-gray-900 mb-8">
    Bound "select" and access selection data
  </h3>
  <div class="flex flex-col w-full md:w-2/3">
    <select 
      x-model="selectedOption" class="inline-block w-full appearance-none bg-white border border-gray-400 hover:border-gray-500 px-4 py-2 pr-8 rounded shadow leading-tight focus:outline-none focus:shadow-outline"
    >
      <option value="">Select an option</option>
      <template 
        x-for="option in options"
      >
        <option :key="option.value" :value="option.value" 
          x-text="option.text"
        ></option>
      </template>
    
        <option :key="option.value" :value="option.value" 
                x-text="option.text" key="bacon" value="bacon"
              >Bacon</option>
      
        <option :key="option.value" :value="option.value" 
                  x-text="option.text" key="ham" value="ham"
                >Ham</option>
      </select>
    <button 
      @click="access()" class="mt-4 w-full bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
    >
      Access Data
    </button>
  </div>
  <label class="block"
  >Output: "<span x-ref="output"></span>"</label>
  <script type="text/javascript">
    function page() {
      return {
        selectedOption: "",
        options: [
          {
            value: "bacon",
            text: "Bacon",
          },
          {
            value: "ham",
            text: "Ham",
          },
        ],
        access() {
          this.$refs.output.innerText = this.selectedOption;
        },
      };
    }
  </script>
</div>

💥 Subscribe for Early Access to the Alpine.js Handbook 📖 💥