Skip to content Skip to sidebar Skip to footer

Set Option 'selected' If Url Query String Matches

I have a select box that filters database results on a page. The value of each option is the query string, starting with ? and then the corresponding name/value pair of particular

Solution 1:

your pretty much there, try this:-

$(document).ready(function() {
  var queryString = window.location.href.slice(window.location.href.indexOf('?'));
  $("#timeline-filter > option").each(function() {
    if (this.value == queryString) {
      this.selected = 'selected';
    }
  });
});

For your alternative, try this:-

var queryString = window.location.href.slice(window.location.href.indexOf('?'));
$("#timeline-filter > option[value='" + queryString + "']").prop('selected', true)

TEST BELOW

var href = "dfgdfgg.html?l=Replaced"

$(document).ready(function() {
  var queryString = href.slice(href.indexOf('?'));
  $("#timeline-filter > option").each(function() {
    if (this.value == queryString) {
      this.selected = 'selected';
    }
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="timeline-filter"onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);"><optionvalue="log">Show All</option><optionvalue="?l=Previewed">Show Previewed</option><optionvalue="?l=Edited">Show Edited</option><optionvalue="?l=Downloaded">Show Downloaded</option><optionvalue="?l=Replaced">Show Replaced</option><optionvalue="?l=Deleted">Show Deleted</option></select>

Post a Comment for "Set Option 'selected' If Url Query String Matches"