Getting Sub Category Base on Selection from main Category Using Jquery or Javascript

Selecting a sub-category after selecting category using jquery, load sub category based on category by calling jquery function, Retrieve Sub-Categories according to Parent category selection

Hi guys today i will tell you through this tutorial that how do you get the value of the related subcategory category in javascript and jquery?

This tutorial will tell you step by step. So let’s go.

First you will create a drop down through the select option tags in html and give some value in the option as you can see below.

getting-sub-category-base-on-selection-from-main-category-using-jquery-or-javascript.html

<!DOCTYPE html>
<html>
<head>
<title>Getting sub-category base on selection from main category Using jquery or javascript</title>
</head>
<body>
<select id="category">
<option value="Fashion">Fashion</option>
<option value="Electronics">Electronics</option>
</select>
<select name="subcategory" id="subcategory">
<optgroup label="Fashion">
<option value="Men's wear">Men's wear</option>
<option value="Women's wear">Women's wear</option>
</optgroup>
<optgroup id="B" label="Electronics">
<option value="Television">Television</option>
<option value="Game Console">Game Console</option>
</optgroup>
</select>
</body>
</html>

After that, you can copy the script code below and paste it in the same page and run it on your server and you can see demo for demo by clicking on the demo link below.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var $optgroups = $('#subcategory > optgroup');
$("#category").on("change",function(){
var selectedVal = this.value;
$('#subcategory').html($optgroups.filter('[label="'+selectedVal+'"]'));
});
});
</script>

You can also combine this code in this way.

getting-sub-category-base-on-selection-from-main-category-using-jquery-or-javascript.html

<!DOCTYPE html>
<html>
<head>
<title>Getting sub-category base on selection from main category Using jquery or javascript</title>
</head>
<body>
<select id="category">
<option value="Fashion">Fashion</option>
<option value="Electronics">Electronics</option>
</select>
<select name="subcategory" id="subcategory">
<optgroup label="Fashion">
<option value="Men's wear">Men's wear</option>
<option value="Women's wear">Women's wear</option>
</optgroup>
<optgroup id="B" label="Electronics">
<option value="Television">Television</option>
<option value="Game Console">Game Console</option>
</optgroup>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var $optgroups = $('#subcategory > optgroup');
$("#category").on("change",function(){
var selectedVal = this.value;
$('#subcategory').html($optgroups.filter('[label="'+selectedVal+'"]'));
});
});
</script>
</body>
</html>