Alpine.js: Cascading Select

Adi Ramadhan
2 min readDec 19, 2024

--

Cascading select. Case: select category-subcategory.

Cascading Select: category-subcategory

create index.html with alpinejs
reference: alpinejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cascading Select</title>
</head>
<body>

<h1>Cascading Select</h1>

<div x-data="{
selectedCategory: null,
subcategories: [],
selectedSubcategory: null
}"
id="category-subcategory-id">

<label for="category">Category: </label>
<select id="category" x-model="selectedCategory" @change="getSubcategories()" class="form-control">
<option value="">--Choose Category--</option>
<template x-for="category in categories">
<option :value="category.id"><span x-text="category.name"></span></option>
</template>
</select>

<label for="subcategory">Subcategory: </span></label>
<select id="subcategory" x-model="selectedSubcategory" class="form-control">
<option value="">--Choose Subcategory--</option>
<template x-for="subcategory in subcategories">
<option :value="subcategory.id"><span x-text="subcategory.name"></span></option>
</template>
</select>

</div>
<script>
const categories = [
{ id: 1, name: 'Electronics' },
{ id: 2, name: 'Clothing' },
{ id: 3, name: 'Food' }
];

const subcategoriesData = {
1: [
{ id: 1, name: 'Laptops' },
{ id: 2, name: 'Phones' },
{ id: 3, name: 'TVs' }
],
2: [
{ id: 1, name: 'Men' },
{ id: 2, name: 'Women' },
{ id: 3, name: 'Kids' }
],
3: [
{ id: 1, name: 'Fruits' },
{ id: 2, name: 'Vegetables' },
{ id: 3, name: 'Dairy' }
]
};

function getSubcategories() {

const alpineComponent = document.getElementById('category-subcategory-id');
const alpineData = Alpine.$data(alpineComponent);
if (alpineData.selectedCategory) {
alpineData.subcategories = subcategoriesData[alpineData.selectedCategory];
} else {
alpineData.subcategories = [];
}
alpineData.selectedSubcategory = null; // Clear subcategory when category changes
}
</script>

<script src="https://unpkg.com/alpinejs" defer></script>
</body>
</html>
  • x-data: Defines reactive data properties:
  • selectedCategory: Stores the currently selected category ID.
  • subcategories: Stores the array of subcategories for the selected category.
  • selectedSubcategory: Stores the currently selected subcategory ID.
  • @change event listener: Triggers the getSubcategories() function when the selectedCategory changes.

--

--

Adi Ramadhan
Adi Ramadhan

No responses yet