Last active
December 6, 2023 17:23
-
-
Save DArmstrong87/2247e279e79aa65943a749f72a8b0b69 to your computer and use it in GitHub Desktop.
Build JS URL and dynamically insert query params based on selected filters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{### FILTERS ###} | |
<select id="filter1" name="filter1"> | |
<option value="" selected disabled>Filter 1</option> | |
<option value="1">One</option> | |
<option value="2">Two</option> | |
</select> | |
<select id="filter2" name="filter2"> | |
<option value="" selected disabled>Filter 2</option> | |
<option value="1">One</option> | |
<option value="2">Two</option> | |
</select> | |
<select id="filter3" name="filter3"> | |
<option value="" selected disabled>Filter 3</option> | |
<option value="1">One</option> | |
<option value="2">Two</option> | |
</select> | |
<script> | |
function buildUrl(){ | |
// Build URL dynamically with query params from filters | |
const queryParams = {}; | |
let filters = [filter1, filter2, filter3] | |
for (const filter of filters){ | |
if (filter[0] !== undefined && filter[0].value !== ""){ | |
queryParams[filter[0].name] = filter[0].value | |
} | |
}; | |
let currentUrl = window.location.href; | |
let url = new URL(currentUrl); | |
url.pathname = "{% url 'django_url_data' %}"; | |
Object.keys(queryParams).forEach(key => url.searchParams.append(key, queryParams[key])); | |
return url | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment