I have a WooCommerce form on the category pages which allows the user to select the number of products to be shown on the page. The values are 24, 48 and all. When one of the options is selected, the form is submitted. The issue I have is the GET value is replacing the existing values in my URL whereas I need the value adding to the end of the URL.
For example, if my URL is: www.example.com/?s=cars&post_type=product&type_aws=true and I update the form, the URL becomes: www.example.com/?show=48 whereas I need it to be added to the end like so: www.example.com/?s=cars&post_type=product&type_aws=true&show=48
Here is my HTML Form:
<form class="woocommerce-results-per-page" method="get">
<span>Show</span>
<select class="autosubmit" name="show">
<option value="48">48</option>
<option value="24">24</option>
<option value="-1">All</option>
</select>
<input type="hidden" name="orderby" value="rating">
</form>
Here is my jQuery
$(function(){
$(document).ready(function()
{
$( '.autosubmit' ).each( function()
{
$( this ).on( 'change' , null , function()
{
$( this ).parents( 'form' ).submit();
});
} );
});
});
Try this:
$(document).ready(function () {
let select = $('.autosubmit');
url = new URL(window.location.href);
show = url.searchParams.get("show");
if (show !== null) {
select.find(`option[value="${show}"]`).prop('selected',true)
}
select.each(function () {
$(this).on('change', null, function () {
let url = window.location.search;
let params = url.substring(1, url.length).split('&');
let hidden_inputs = '';
let form = $(this).parents('form');
$.each(params, function (i, el) {
let param = el.split('=');
if (form.find(`select[name="${param[0]}"],input[name="${param[0]}"]`).length == 0) {
hidden_inputs += `<input type="hidden" name="${param[0]}" value="${param[1]}">`;
}
});
form.prepend(hidden_inputs).submit();
});
});
});