Skip to content

Commit

Permalink
[TASK] Make sure GET parameters from search and sorting are kept
Browse files Browse the repository at this point in the history
  • Loading branch information
MattiasNilsson committed Oct 31, 2024
1 parent f3cd4cc commit 83fc89b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions theme/modules/product-list.module/module.html
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@
<div class="product-listing-module__search">
<form action="{{ request.path }}" class="row-fluid">
<input type="text" name="qd_name" value="{{ qd_name }}">
{% if request.query_dict %}
{% for key, value in request.query_dict.items() %}
{% if key != 'qd_name' %}
<input type="hidden" name="{{ key }}" value="{{ value }}">
{% endif %}
{% endfor %}
{% endif %}
<button type="submit" class="btn-link btn-regular">{{ searchLabel }}</button>
</form>
</div>
Expand Down
47 changes: 47 additions & 0 deletions theme/modules/product-list.module/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,55 @@ function changeSorting (event) {
}
}

function addEventListenerToFilters () {
document.addEventListener('DOMContentLoaded', function () {
function buildQueryString () {
const queryString = window.location.search
const urlParams = new URLSearchParams(queryString)
const params = {}
for (const [key, value] of urlParams.entries()) {
params[key] = value
}
let queryStringMerged = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&')

if (queryStringMerged) {
queryStringMerged = '&' + queryStringMerged
}

return queryStringMerged
}

function appendToLinks (selector, queryString, excludeParams = []) {
const container = document.querySelector(selector)
const selects = container.getElementsByTagName('select')

const urlParams = new URLSearchParams(queryString)
excludeParams.forEach(param => urlParams.delete(param))
const filteredQueryString = urlParams.toString() ? '&' + urlParams.toString() : ''

for (let i = 0; i < selects.length; i++) {
const options = selects[i].getElementsByTagName('option')
for (let j = 0; j < options.length; j++) {
const currentHref = options[j].getAttribute('value')
if (currentHref.includes('?')) {
options[j].setAttribute('value', currentHref + filteredQueryString)
} else {
options[j].setAttribute('value', currentHref + '?' + filteredQueryString.substring(1))
}
}
}
}

const queryString = buildQueryString()
appendToLinks('.product-listing-module__sorting-filter', queryString, ['qd_sorting'])
})
}

function init () {
addListener()
addEventListenerToFilters()
}

init()

0 comments on commit 83fc89b

Please sign in to comment.