Skip to content

HTML Easiest Way To Change Subcategory Options Based On Category Dropdown

I had to deal with this frustrating issue recently in a huge project and it even works for sub-sub-category. You just have to work around the attribute names you give. So you currently have a <select> for your category and sub-category already, that would probably look something like this for your category,
<select class="form-control" id="assigned_school" name="assigned_school">
    <option value="1" selected>School 1</option>
    <option value="2">School 2</option>
and this for your sub-category,
<select class="form-control" id="assigned_class" name="assigned_class">
        <option value="1">Class 1</option>
        <option value="2" selected>Class 2</option>
So.. now, how do we get this implemented easily? You will first need to make sure your sub-category <option> knows the parent category’s value or id – basically a way to identify the parent category. I do so by adding an attribute named parent_category , as shown below.
<select class="form-control" id="assigned_class" name="assigned_class">
        <option parent_category="1" value="1">School 1 Class 1</option>
        <option parent_category="1" value="2" selected>School 1 Class 2</option>
        <!-- add more options -->
        <option parent_category="2" value="1">School 2 Class 1</option>
        <option parent_category="2" value="2" selected>School 2 Class 2</option>
Great, with this we have a relationship between our category and sub-category that we can use in our Javascript / JQuery code. Now we need this quick function to help us show and hide our sub-category dropdown options.
// taken from stackoverflow. can't remember the url.
jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        if( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
            jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
Now that we are able to hide or display our drop down options, finally we need to detect when the parent category dropdown value changes (user selects another option)
    $('#assigned_school').on('change', function() {
        var option_value = this.value;
        jQuery("option[parent_category='" + option_value + "']").toggleOption(true); // show option
        jQuery("option[parent_category!='" + option_value + "']").toggleOption(false); // hide option

As simple as that.    
Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *