So basically, I have this code taken from Advanced Custom fields Ressource center:
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="checkbox"]', function(){
// vars
var url = '<?php echo '//' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>';
args = {};
// loop over filters
$('#archive-filters .filter').each(function(){
// vars
var filter = $(this).data('filter'),
vals = [];
// find checked inputs
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
if (url.indexOf('?') > -1){
//code
url += '&';
}
else {
url += '?';
}
// loop over args
$.each(args, function( name, value ){
if (value==='') {
url += '';
}else {
url += name + '=' + value + '&';
}
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>
When I check a checkbox in #archive-filters
div, it reloads the page with the new parameter in url.
Now I Would like to remove the parameter when the checkbox is unchecked but can’t find How.
How can I remove the url parameter associated to the checkbox unchecked?
2
Answers
The easiest way to handle all of this is with the URL API and URLSearchParams
I’m not 100% clear what the search params look like for that WP plugin so have used some very simple ones and am only using their keys to match checkbox names .
Also not sure if the active ones are checked or not on page load but show how to do it here if they are not
Since the URL object can be updated as many times as you need it may also offer you an alternative to reloading every time checkbox is checked and allow users to make multiple selections before reloading
Very good code, I used it to add or remove a DEBUG flag in the URL.
To have the URL like:
Here is my modified version: