Skip to main content
edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
Bumped by Community user
Source Link
Nix
  • 111
  • 1
  • 3

Change URL on select change

I've made a method, which inserts a new query parameter, when the value of a select changes, then reloads the page. I've had enough of URL jQuery hax, so I figured it would be a great idea to put the query parameters in an array, and manipulate it that way. I'm a little unsure whether or not this is the best way of doing it, so some input would be appreciated.

HTML

<select id="selCurrency">
   <option value="">Choose currency &hellip;</option>
   <option value="DKK">Danske kroner</option>
   <option value="NOK">Norske kroner</option>
   <option value="SEK">Svenske kronor</option>
</select>

JS

$("#selCurrency").change(function(){
     var val = $(this).val(); // This should be the new CurrencyCode, extracted from a select box 
     var pag = window.location.pathname;
     var url = window.location.search;
         url = url.replace("?", "").split("&"); // Clean up the URL, and create an array with each query parameter
     
     var n = 0;
     for (var count = 0; count < url.length; count++) {
         if (!url[count].indexOf("CurrencyCode")) { // Figure out if if/where the Currency is set in the array, then break out
             n = count;
             break;
         }
     }
     
     if (n !=0) {
        url.splice(n,1); // If the Currency was set, remove it from the array
     }

     var len = url.length;
     var newUrl = url.join("&"); // Restringify the array

     if (len > 0) { // Check whether or not the currency is the only parameter, then build new URL with ? or &
        newUrl = pag + "?" + newUrl + "&CurrencyCode=" + val;
     } else {
        newUrl = pag + newUrl + "?CurrencyCode=" + val;
     }
     
     window.location.href = newUrl; // Finished, let's go!
  });

You will notice, that I've used the jQuery selector engine, while the rest is native JS. Would it be smarter/faster to use native JS to check for the onchange event?

document.getElementById("selCurrency").onchange( /* My function right here, mayn */ );