1

I search through many websites, but I dont finde the right solution, so I don´t really know if its possible ...

I have a dropdown:

<select name="filter">
  <option selected value="">All</option>
  <option value="newest">Newest</option>
</select>

... and some divs with the informations. So, the classic way is to press the dropdown and select an option. But what I want is to select the dropdown value by url ...

For example: If "url + newest" > select "filter" = value "newest"

URL example: www.mypage.com/hotels&newest

Is that possible? Any simple way?

Pepe
  • 663
  • 5
  • 17
  • 1
    The URL of what - the current page? "newest" wouldn't be a valid URL so I'm not sure what you mean. – cjol Aug 20 '15 at 09:01
  • Yes it is - you would have to parse the current URL with javascript and make the selection "manually" according to the contents of the URL. Take a look at [this post](http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript). – Lix Aug 20 '15 at 09:02
  • @Hephistocles: I add an url example on top ... (at)Lix: ok, I will take a look. – Pepe Aug 20 '15 at 09:05
  • So give us an exact URL :) ... www.mypage.com/hotels&newest ? ... or www.mypage.com/hotels=newest ... or www.mypage.com/?hotels=newest :) – pesho hristov Aug 20 '15 at 09:05

2 Answers2

3

You could do something like this:

// Run on document ready
$(function() {
   // If the current url contains the string '&newest'
   if (document.location.href.indexOf('&newest') > -1)
   {
      // Use jQuery to set the value of the select box to 'newest'
      $('[name=filter]').val('newest');
   }
});

Then simply add extra else/if statements as needed if there are more options you need to cater for ...

HaukurHaf
  • 12,423
  • 5
  • 35
  • 52
0

To get the value of the URL query string, do something as suggested by Lix in the comments:

var item = document.location.href.match(/&(.*)$/)[1]

To then make the selection, something like this (note you'll need to set id="filter" on the select:

​document.getElementById('filter').value = item;​​​​​​​​​​

Note that typically the URL hash is used for this, so your URL would look like this instead: `www.mypage.com/hotels#newest'. With your URL in this format, you don't need to do any regex matching, you can simply do

var item = document.location.hash.substr(1)

(the .substr(1) bit is just to get rid of the leading hash sign)

cjol
  • 1,311
  • 7
  • 22
  • The benefit of this solution is that you don't need to add extra code if you add new options. If you only have one option to worry about ("newest"), then HaukurHaf's is probably easier! – cjol Aug 20 '15 at 09:29