I am trying to add value of each checkbox to URL
searchParams, first time when I check a checkbox it works good, but when I reload page, it not work anymore, what I have done wrong? I mean it works when it is state
but after page load, not working, how can I fix this?
function setURL(query){
//var url = window.location.protocol "//" window.location.host window.location.pathname;
var url = window.location.href;
let newURL = new URL(url);
newURL.searchParams.append('brands', query)
window.history.replaceState(null, null, newURL);
}
function checkURL(){
var url = window.location.href;
let newURL = new URL(url);
window.history.replaceState(null, null, newURL);
if(newURL.searchParams.has('brands')){
let currentBrands = newURL.searchParams.get('brands');
let brandsArray = currentBrands.split(',');
brandsArray.map(function(v,i){
jQuery('input[name="pa_brand"][value="' v '"]').click();
});
}
}
checkURL();
let array = [];
jQuery('input[name="pa_brand"]').change(function(){
let value = this.value;
let id = array.indexOf(value);
if(jQuery(this).is(':checked')){
array.push(value)
} else {
array.splice(id, 1);
}
setURL(array.toString())
console.log(array)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="pa_brand" value="116"/>
<input type="checkbox" name="pa_brand" value="117"/>
<input type="checkbox" name="pa_brand" value="118"/>
CodePudding user response:
First of all replace newURL.searchParams.append('brands', query)
with newURL.searchParams.set('brands', query)
. It will solve your problem also in the checkURL
put initial value to array
variable. I edited your code after these two changes and everythin seems ok.
let array = [];
function setURL(query){
//var url = window.location.protocol "//" window.location.host window.location.pathname;
var url = window.location.href;
let newURL = new URL(url);
newURL.searchParams.set('brands', query)
window.history.replaceState(null, null, newURL);
}
function checkURL(){
var url = window.location.href;
let newURL = new URL(url);
window.history.replaceState(null, null, newURL);
if(newURL.searchParams.has('brands')){
let currentBrands = newURL.searchParams.get('brands');
let brandsArray = currentBrands.split(',');
array = brandsArray;
brandsArray.map(function(v,i){
jQuery('input[name="pa_brand"][value="' v '"]').click();
});
}
}
checkURL();
jQuery('input[name="pa_brand"]').change(function(){
let value = this.value;
let id = array.indexOf(value);
if(jQuery(this).is(':checked')){
array.push(value)
} else {
array.splice(id, 1);
}
setURL(array.toString())
console.log(array)
})