1

I'm currently passing a variable to query string with select drop downs and jQuery using this:

$("#filter_1").change(function(e) {
  window.location.href = '?filter_1=' + $(this).val()
});
$("#filter_2").change(function(e) {
  window.location.href = '?filter_2=' + $(this).val()
});

This is working great. However, if you select filter_2 after having already passed the filter_1 variable, filter_1 gets overwritten in the query string. What I need now is a way to append the filter_1 and filter_2 and vice-a-versa. Any ideas?

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • 1
    Changing the queryparam reloads the page. Are you also setting the value of the selects based on the params when the page loads? – Kevin B Aug 09 '12 at 15:33
  • To add to Kevins response. Every time page loads your select would loose the selected previously value. You need to handle it by passing the selection to server and restoring it upon page load. – anazimok Aug 09 '12 at 15:55

1 Answers1

0

Here you create a function which parses the query string for you and returns key=value of the requested key if it exists or just an empty string if it doesn't.

$("#filter_1").change(function(e) {
   window.location.href = '?filter_1=' + $(this).val() + 
      querystring('filter_2', '&');
});
$("#filter_2").change(function(e) {
   window.location.href = '?filter_2=' + $(this).val() + 
      querystring('filter_1', '&');
});


function querystring(name, prefix)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return '';
  else
    return (prefix||'')+name+'='+ decodeURIComponent(results[1].replace(/\+/g, " "));
}

Function originates from: How can I get query string values in JavaScript?

Community
  • 1
  • 1
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • This was really close! I had to edit your code slightly, but it was 99% what I needed. Thank you! I had to add the "&" separator to connect to the two variables: 'window.location.href = '?filter_1=' + $(this).val() + '&' + querystring('filter_2');' – Jacob Wadenpfuhl Aug 09 '12 at 17:40
  • I would totally upvote but it looks like I don't have enough "reputation" yet. – Jacob Wadenpfuhl Aug 09 '12 at 18:00