Hi everyone
I'm working on a commerce project which needs dynamic selects depending on each other for product attributes: for example consider Size, Weight and Color:
<div class="bg-white" x-data="{
attributes:[
{'name':'size','label':'Size','desc':'Size field description'},
{'name':'weight','label':'Weight','desc':'Weight field description'},
{'name':'color','label':'Color','desc':'Color field description'}
],
products:[
{'id':1, 'size':'small', 'weight':'1 kg', 'color': 'red', 'price': 100},
{'id':2, 'size':'small', 'weight':'1 kg', 'color': 'blue', 'price': 200},
{'id':3, 'size':'small', 'weight':'2 kg', 'color': 'green', 'price': 300},
{'id':4, 'size':'small', 'weight':'2 kg', 'color': 'yellow', 'price': 400},
{'id':5, 'size':'large', 'weight':'4 kg', 'color': 'pink', 'price': 500},
{'id':6, 'size':'large', 'weight':'4 kg', 'color': 'navy blue', 'price': 600},
{'id':7, 'size':'large', 'weight':'4 kg', 'color': 'cyan', 'price': 700},
{'id':8, 'size':'large', 'weight':'6 kg', 'color': 'amber', 'price': 800},
{'id':9, 'size':'large', 'weight':'6 kg', 'color': 'black', 'price': 900}
],
selected: {}
}" >
<ul>
<template x-for="(attribute, index) in attributes">
<div>
<label for="attribute.name" x-text="attribute.label"></label>
<select name="attribute.name" id="attribute.name" @change="selected[attribute.name] = $el.value; console.log(selected);">
<template x-for="product in products.filter((p) => Object.keys(selected).every((k) => selected[k] === p[k]))">
<option :value="product[attribute.name]" x-text="product[attribute.name]"></option>
</template>
</select>
</div>
</template>
</ul>
</div>
In this example I want to have three select menus for each attribute which contains correct options: for example in the data below you select size between 'small' or 'large' then values in the second select will change according to that and then color the same way and finally show the correct selected price.
I have some problems:
- repeating values of attributes! should I create separate array for each attribute containing all values? what can I do for it?
- Its not possible to select another options once you select something
Could you please shed some light on it and guide me on a proper way to do it?
P.S. I'm doing this Laravel and Alpinejs so I can create extra functions, data sets and during server side rendering...
Thanks a lot in advance