1
votes

Show Sub Category based on Category - - Check out this image.

I want that when someone selects any category then the sub category displays choices based on that particular category that was selected. I'm learning PHP/MySQL but I know the basics of Javascript. Can any teach me in a simple way how it can be done with JavaScript or JQuery?

Categories and sub categories are showing perfectly in the dropdown but are showing all the Sub-Categories and Categories.

<div>
  <label>Category</label>
  <select name="category">
    <option value="0" disabled selected>Select Category</option>
    <?php
    $cdata = $dbobj->getCategories(0);
    while($crow = mysql_fetch_array($cdata)){?>
    <option value="<?php echo $crow["categoryid"]; ?>"><?php echo $crow["category_name"]; ?></option>
    <?php } ?>
  </select>
</div>
<div>
  <label>Sub Category</label>
  <select name="subcategory">
    <option value="0" disabled selected>Select Category</option>
    <?php
    $scdata = $dbobj->getSubCategories(0);
    while($scrow = mysql_fetch_array($scdata)){?>
    <option value="<?php echo $scrow["subcategoryid"]; ?>"><?php echo $scrow["subcategory_name"]; ?></option>
    <?php } ?>
  </select>
</div>

Thanks

Categories & Sub Categories

Men

  • Clothes
  • Shoes

Women

  • Jewelry
  • Sarees
  • Shoes

Kids

  • Toys
  • Clothes

Books

  • Language
  • Fiction

What I want is - whenever someone chooses the category Men, only two subcategories, Clothes and Shoes show up.

1

1 Answers

0
votes

Using JQuery :

$(function(){
    $(".category option").click(function(){
        $(".category").parent().css("display", "none"); // Targetting the parent and hide
        $(".subcategory").parent().css("display", "block"); // Targetting the parent and show
    });
    $(":not(.category option)").click(function(){
        // If click on other thing than category option then show
        $(".category").parent().css("display", "block");
    });
});

EDIT : Added the possibility to return to category