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.
first_filter_name=325,first_filter_name=326,first_filter_name=327,second_filter_name=225,second_filter_name=228
So now how to convert this array and make single url with repeated params?
Expected url will be :http://localhost.com/page.html?first_filter_name[0]=72&first_filter_name[1]=83&first_filter_name[2]=84&second_filter_name[0]=brand1&second_filter_name[1]=brand2
.
Our filters look like
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
3
Answers
Take a look at the snippet below. Basically the idea is to fetch all checkboxes with the appropriate selector (in my sample,
[data-my-form] input[type="checkbox"]:checked
, but can be anything else), and then calljQuery.serialize()
on them.The
decodeURIComponent
part is just forconsole.log
, you don’t want to decode that if you’re gonna use it as an actual URL.Note that inputs’ names could all be
foo[]
(without indexes) and that would also generate a valid URL.You can use
reduce
to create the array of values and then usejoin
to concat into a string:or
result example =>
values = ["Hourly", "Daily", "Weekly", "Monthly", "Yearly"]