-1

Say for instance that my URL could have an appended query string (i.e. "&sort="). How can I check for that query value and then make a drop-down list show the same selected value?

Example:

URL could be: example.com/Pages/default.aspx?Type=2&sort=price

or sort may not exist if nothing has been selected.

<select name="SortBy" id="SortBy">
  <option selected="selected" value="Item Number">Item Number</option>
  <option value="Price">Price</option>
  <option value="Weight">Weight</option>
  <option value="Date">Date</option>
</select>

I need to take that sort value in the URL and set instead:

<select name="SortBy" id="SortBy">
  <option value="Item Number">Item Number</option>
  <option selected="selected" value="Price">Price</option>
  <option value="Weight">Weight</option>
  <option value="Date">Date</option>
</select>

Thanks.

Justin Hollender
  • 363
  • 1
  • 3
  • 10

1 Answers1

0
// check for query parameters
if (window.location.search){
  // grab the `sort=foo` portion
  var sort = window.location.search.match(/sort=([^&]+)/);
  // check if it's there
  if (sort){
    // get the value portion
    var sortValue = sort[1].toLowerCase();
    // because there's a potential cASe difference, iterate over the options
    // and mark the matching entry based on value
    $('#SortBy option').each(function(){
      var $option = $(this);
      if ($option.prop('value').toLowerCase() == sortValue){
        $option.attr('selected','selected');
        return false; // "break;"
      }
    });
  }
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200