Magento – Magento 2: How to create multiple select filters with apply button in layered navigation

magento-2.1multiple-select-layered

We are trying to add multiple select filters to apply button for layered navigation in Magento 2.1.0 with Smile Elastic Suite.

I have created a jQuery script to get all multiple selected option and split taking only params in array like below.

isconsumablefor=325,isconsumablefor=326,isconsumablefor=327,sets_pcs=225,sets_pcs=228

So now how to convert this array and make single url with repeated params?

Our filters look like

enter image description here

My script is like :

 $(".apply-filters").on("click",function(e){
         e.preventDefault();
            var val=[];
            var queryString= [];
            var hash;
            $("input[name='type']:checked").each(function() {                    
            val.push($(this).val().slice($(this).val().indexOf('?') + 1).split('&'));

            });
           alert(val);
        });

Alert result is:

isconsumablefor=325,isconsumablefor=326,isconsumablefor=327,sets_pcs=225,sets_pcs=228

So help me to create single url to load products using filter params

in website multi attribute select will be like below "http://localhost/magento2/shop/kitchen.html?attribute1[0]=20&attribute11=30&attribute2[0]=21" so i am not getting the checked box value only for same attribute

Best Answer

url for multiple select looks like:

http://localhost.com/page.html?first_filter_name=72,83&second_filter_name=brand1,brand2

All values which belong to the same filter must be separated by commas

try it. It is hard-code, but i think you are able to understand logic

<script>
function search(name, value) {
    this.name = name;
    this.value = value;
}

$(".apply-filters").on("click", function (e) {
    e.preventDefault();
    var obj = [];
    var value = [];
    var queryString = window.location.pathname+'?';

    $("input[name='type']:checked").each(function () {
        var temp = $(this).val().split('=');
        obj.push(new search(temp[0], temp[1]));
        if (value.indexOf(temp[0]) == -1) {
            value.push(temp[0]);
        }
    });

    value.forEach(function (item) {
        queryString+= item + '=';
        obj.forEach(function (o) {
            if (o.name == item) {
                queryString+= o.value+',';
            }
        })
        queryString=queryString.substring(0, queryString.length - 1);
        queryString+='&';
    })
    queryString=queryString.substring(0, queryString.length - 1);

    $(location).attr('href', queryString);
});