Creating a Simple Shopping Cart Application - Step 5 - Adding a Search Filter

*** The technique used in the following Post is only available if you are using the Bootstrap 5 version of the Shopping Cart -- see Posts at the beginning of the Shopping Cart Section ***

Now that we have a d-flex grid (which is based on a css flexgrid) it is relatively straightforward to introduce a search filter. All we have to do is show or hide certain elements of the grid based on their class. Because the grid is flexible it will instantly redraw. First, modify the file /resources/views/products/displaygrid.blade.php and add the following classes to the div which controls each panel in our shop window.

The allcolours class will allow us to refer to all the products so we can show/hide them as necessary where the {{$product->colour}} class allows us to refer to groups of products by their colour.

Next add the following code for a select tag which creates a dropdown list full of possible colours for the user to choose from

        <li class="nav-item" style="margin-right:5px;">
            <select id="colourselect" class="form-select" size="1">
                <option value="All">All</option>
                <option value="Blue">Blue</option>
                <option value="Red">Red</option>
                <option value="Green">Green</option>
                <option value="Yellow">Yellow</option>
                <option value="Orange">Orange</option>
            </select>   
        </li>

Place this code inside the Shopping Cart Navigation Bar here

Finally, we need to add some jquery code which will react on an onChange event of our new #colourselect dropdown. This means the event will only fire after the user has chosen a different colour from the list other than the one that is already selected. When the option changes the code will hide all the colours and then "show" the colour which has been selected from the dropdown by the user.

Place the following function inside script tags before the @endsection blade directive at the bottom of the page

<script>
$("#colourselect").on('change', function() {
    var colour = $(this).find(":selected").val();
    if (colour=='All') {
        $('.allcolours').show();
    }
    else {
        $('.allcolours').hide();
        $('.'+colour).show();
    } 
});
</script>

The code should be located as follows

Now when you select your preferred colour from the dropdown only items of that colour will be displayed.