-1

Im trying to auto select a option of the state dropdown box with the variable from the url.

For some reason in Safari only, I get this message (undefined is not an object (evaluation 'params.get')) -- not sure why, it only happens in Safari. It works perfect in FF and in Chrome. any thoughts why? Any way to change code to work across all browsers?

jQuery(document).ready(function( $ ) {

 // Construct URL object using current browser URL
  var url = new URL(document.location);

  // Get query parameters object
  var params = url.searchParams;

  // Get value of state
  var state = params.get("state");
   state = state.toUpperCase();
//alert(state);



$('#state option').each(function(){
    var $this = $(this); // cache this jQuery object to avoid overhead

    if ($this.val().toUpperCase() == state) { // if this option's value is equal to our value
        $this.prop('selected', true); // select this option
        return false; // break the loop, no need to look further
    }
});

});
DEM
  • 333
  • 2
  • 4
  • 16
  • Likely due to [URLSearchParams browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility), though Safari's support in particularly seems to be up in the air. Given that it works in other browsers though, you'll probably need to use a vanilla function (in the dupe that @Taplar has linked to) – Tyler Roper Dec 03 '18 at 18:25

1 Answers1

2

If I want to get query strings from URL, I use the below code snippet, it is very straightforward

 var queryStrings = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    var pageParams = [];
    for (var i = 0; i < queryStrings.length; i++) {
        var hash = queryStrings[i].split('=');
        var qKey = hash[0];
        var qVal = hash[1];
        pageParams.push({Key: qKey, Value: qVal});      
    }
    

then you have all query string Key/Value params in pageParams variable