Skip to content
Advertisement

subcategory will not show as parent category

I am trying to get my subcategory based on the category here is my code

JavaScript

the jquery

JavaScript

but it will only show the last category’s subcategories how can I fix this?

alternatively i was using this code before

JavaScript

jquery

JavaScript

but since I need 2 selects one individually for sub-categories that I can put an onchange=”filter(this)” for it that show the result only based on the subcategory I’ve changed my code to first part so if there is a way that I can do that in the second part that can fix my problem too

Advertisement

Answer

Looking at your originally posted code let’s review what it’s doing:

JavaScript

Since PHP is processed on the server side and no other AJAX calls are in play here the line $sub_categories = $this->crud_model->get_sub_categories($category['id']); will only ever produce the sub-categories to the last category in the block above. This is the root of your problem, you needed to iterate over the categories again to get the sub-categories for each category.

I have altered your code combining the two together to show what changes were made to foreach over the categories, jQuery.hide() the subcategory selects, and then jQuery.show() only the one selected when a category is selected.

JavaScript

The changes include looping over the categories again to get all the subcategories that’s why you only have the last one.

The next thing was to use the category id to be unique in the subcategory groups.

Following by using the proper for attribute on the labels for ADA compliance.

Adding a subcategory class on the <select> tags so that you can find (and hide) all the ones initially and then show only the one that they picked.

EDIT: Changed to use the $category['slug'] instead of $category['id'] per specifications not listed in original request

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement