0

I have a script that adds a parameter to the url on a click - and replaces the the parameter with another on the second click. This works great.

However there is a scenario when there already is a parameter in place - and I then need this click to replace that value.

Example:

Click one gives

?param=largegrid 

Second one replaces the value and gives

?param=smallgrid

But sometimes the url looks like this:

?param=grid or param=grid&fss=tablet

in this case i want the click to replace the first value so the url looks like

?param=large or param=largegrid&fss=tablet 

and the same for the second click.

$('.click10').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=largegrid') > -1) {
url = url.replace("?param=largegrid", "") + '?param=smallgrid'
} else {
url = url.replace("?param=smallgrid", "") + '?param=largegrid'
}
window.location.href = url;
});
Dane
  • 1,191
  • 7
  • 16
user3344734
  • 707
  • 1
  • 4
  • 13

3 Answers3

1

You can try this, search for the param of either grid or large-grid and next you can replace them alternatively.

if (url.indexOf('?param=grid') > -1) {
url = url.replace("grid", "") + 'largegrid'
} else if(url.indexOf('largegrid') > -1) {
url = url.replace("largegrid", "") + 'smallgrid'
} else if(url.indexOf('smallgrid') > -1) {
url = url.replace("smallgrid", "") + 'largegrid'
}
Sravan
  • 16,897
  • 2
  • 24
  • 48
0

You can use the regex for that like

url= url.replace(/(largegrid=)[^\&]+/,updated_largegrid);

Update

Okay what you can do is(as per your posted code) :

  • Have the onclick function
  • Inside that use var url = window.location.href;
  • Now replace all the variables like url= url.replace(/(largegrid=)[^\&]+/,updated_largegrid);
  • You are good to go now
Tushar
  • 11,306
  • 1
  • 21
  • 41
0

I can recommend to library URI.js. It helps parsing and building URIs/URLs. For example, you don't need to worry if the query parameter already exists:

For example, both

var newURL = URI("http://www.example.com/").setQuery("param", "smallgrid").toString();

and

var newURL = URI("http://www.example.com/?param=largegrid").setQuery("param", "smallgrid").toString();

both result in http://www.example.com/?param=smallgrid

An example for your event handler using a callback:

$('.click10').on('click', function() {
  var url = window.location.href;

  url = URI(url).search(function(queryData) {
      queryData.param = (queryData.param === "largegrid") ? "smallgrid" : "largegrid";
  });

  window.location.href = url;
});
RoToRa
  • 34,985
  • 10
  • 64
  • 97