Filtering Values of HTML Element Select using Jquery

HTML Forms Filtering Values of HTML Element Select using Jquery

Goal

When category 1 is selected, items 1, 2, 3 should be shown in the second select. When category 2 is selected, items 4, 5, 6 should be displayed in the outer selection.

HTML

Creating HTML form select with item categories

<select class="form-select" id="categories">
    <option value="1">Category 1</option>
    <option value="2">Category 2</option>
</select>

Creating HTML form select with items and data-category attributes

<select class="form-select" id="items">
    <option data-category="0" value="0">All Items</option>
    <option data-category="1" value="1">Item 1</option>
    <option data-category="1" value="2">Item 2</option>
    <option data-category="1" value="3">Item 3</option>
    <option data-category="2" value="4">Item 4</option>
    <option data-category="2" value="5">Item 5</option>
    <option data-category="2" value="6">Item 6</option>
</select>

Jquery

$(document).ready(function() {

    // Init items select rendering
    renderItems();

    // Rendering items select when category is change
    $("body").on("change", "#categories", function () {
        renderItems();
    });

    // Rendering items select according to category
    function renderItems() {
        //
        var categoryId = $("#categories").val();

        //
        $("#items option").each(function() {
            if ($(this).data("category") == categoryId || $(this).data("category") == "0") {
                $(this).show();
                
                // Select "All Items" option
                if ($(this).data("category") == "0") {
                    $(this).prop('selected', true);
                }
            } else {
                $(this).attr('selected', false);
                $(this).hide();
            }
        });
    }
});

Notice

  1. The script hides the options inside select but does not hide the selected option. So you need to set the selected option every time after options rendering.

  2. You can hide the select option in other ways.

Use

$(this).attr('hidden', true);
$(this).attr('hidden', false);

Instead

$(this).show();
$(this).hide();