This is a change in the GET parameters in the url

The fact is that when you click on the name ulr = index?sort=name , and when you click on nums ulr = index?sort=nums , but you need the result to be ulr = index?sort=name&sort=nums

 <a onclick="return setAttr('sort','name')">по name</a> <a onclick="return setAttr('sort','nums')">по nums</a> <script> function setAttr(prmName,val){ var res = ''; var d = location.href.split("#")[0].split("?"); var base = d[0]; var query = d[1]; if(query) { var params = query.split("&"); for(var i = 0; i < params.length; i++) { var keyval = params[i].split("="); if(keyval[0] != prmName) { res += params[i] + '&'; } } } res += prmName + '=' + val; window.history.pushState(null, null, base + '?' + res); return false; } </script> 
  • if(keyval[0] !== prmName && keyval[1] !== val) - vp_arth
  • @vp_arth tried your option, it still changes and does not add - Ruslan Liashenka

2 answers 2

I made a little mistake in the comments:

 if(keyval[0] != prmName || keyval[1] != val) { res += params[i] + '&'; } 

Feeddle


You can add a check for the current value and remove it:

 if(keyval[0] == prmName && keyval[1] == val) { exists = true; } else ... 

And then check and not add this parameter.

Feeddle

  • Thanks for the answer, everything works !! - Ruslan Liashenka
  • Only now there is one question, and you can implement the deletion, suppose that the click is made on the checkbox - Ruslan Liashenka
  • it may be necessary to check if it is pressed again, if it doesn't exist, tell me how you can do it, just in javascript is still not strong - Ruslan Liashenka
  • need to learn .. The task is not as simple as it seems at first glance. The best thing is to correctly parse the query into an object, modify it and then re-assemble it ... - vp_arth
  • @harbor, do not miss the update in the answer, most likely it solves your problem. - vp_arth

So you can try:

 function setAttr(prmName, val) { var el = prmName + '=' + val; var res = ''; var d = location.href.split("#")[0].split("?"); var base = d[0]; var query = d[1]; if (query) { var params = query.split("&"); for (var i = 0; i < params.length; i++) { if (params.includes(el)) { console.log('Значение уже содержится'); //console.log(location.href); return false; }else{ res += params[i] + '&'; } } } res += el; window.history.pushState(null, null, base + '?' + res); console.log(base + '?' + res); return false; } 
 <a onclick="return setAttr('qsort','name')">qsort name</a> <a onclick="return setAttr('sort','name')">sort name</a> <a onclick="return setAttr('sort','nums')">sort nums</a> 

In the condition, we check the presence of such an element with a key and a value in the params parameter array.

  • you determine that the value is already contained, you can delete it is valid through unset ? - Ruslan Liashenka