i am trying to add a parameter to the current url on click on a div so that i dont loose other paraments and also get some new paraments
<div class='tabes_09o12rt' onclick="window.location.search += '&sort=FOO';">
<div class='tabes_09o12rt' onclick="window.location.search += '&sort=BAR';">
this is working fine but when i click on first div it adds the paramenter FOO to the url and when i click the div 2 it adds the paramenter BAR with the same neme, what i want is that if the paramenter is already added with that name then change it with new name and if not added then add, and on double click remve that paramenter. can we do that ???
Of course we can do that. Just store the original string and retrieve it in a function.
<script type="text/javascript">
var origin = window.location.search;
function sort(method) {
window.location.search = origin + '&sort=' + method;
}
</script>
<div onClick="sort(foo)">Sort using foo</div>
<div onClick="sort(bar)">Sort using bar</div>
Parse the URL and then use the URLSearchParams API to manipulate it instead of blindly appending.
const url = new URL(location);
console.log("Original", url.toString());
url.searchParams.set("sort", "foo")
console.log("Foo", url.toString());
url.searchParams.set("sort", "bar")
console.log("Bar", url.toString());
// location = url;
</div>