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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With