jmadd
jmadd

Reputation: 125

AlpineJS for dynamic select menu

Would like to be able to use Alpine.js to for a dropdown select form. When you select a particular option from the select menu the page insert a set of related records. How would I accomplish something like this with Alpine.js

For example

  1. Select from USA, Canada and Mexico from the select menu. Assume USA was selected
  2. Retrieve a list stores in the USA. (I know I would query this via PHP, sending a param)

Upvotes: 9

Views: 20022

Answers (1)

Hugo
Hugo

Reputation: 3888

You could do something like this (assuming you have all the data beforehand)

<div 
  x-data="{ selectedCountry: null, countries: [ 'Mexico', 'USA', 'Canada' ], storesByCountry: { 'USA': [ { 'store' : 'data' } ] } }"
>
  <select x-model="selectedCountry">
    <template x-for="country in countries" :key="country">
      <option :value="country" x-text="country"></option>
    </template>
  </select>
  Stores:
  <template x-for="store in storesByCountry[selected country] || []" :key="store.id">

  </template>
</div>

If you don't have the data you'll need to do something like this

<div 
  x-data="{ selectedCountry: null, countries: [ 'Mexico', 'USA', 'Canada' ],  stores: [ { 'store' : 'data' } ] }"
  x-init="$watch('selectedCountry', (country) => { fetch('url?country=" + country).then(res=> res.json()).then((storeData) => { stores = storeData }) })"
>
  <select x-model="selectedCountry">
    <template x-for="country in countries" :key="country">
      <option :value="country" x-text="country"></option>
    </template>
  </select>
  Stores:
  <template x-for="store in stores" :key="store.id">

  </template>
</div>

Upvotes: 20

Related Questions