Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlpineJS for dynamic select menu

Tags:

alpine.js

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)

like image 825
jmadd Avatar asked May 08 '20 17:05

jmadd


1 Answers

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>
like image 65
Hugo Avatar answered Sep 22 '22 23:09

Hugo