views:

25

answers:

2

I have a model of objects in a dropdown menu:

<select id="group_select" name="group_select">
    <option value="1">Group One</option>
    <option value="2">Group Two</option>
</select>

Each corresponding object has a detail page in which I want to have a link that sends the user to the page with the dropdown menu with the object they were referred from already selected in the menu. I was thinking that this could be done with a query string, but I seem to be mistaken. (e.g. /rank/objects/?group_select=1.

What would be the proper way to do this? Answers with jQuery are welcome as well, since I'm already using that on this page.

Thanks!

+2  A: 

yes it could.

first of all, we need to create a function to parse the query string.

function queryString(key) {

  var longurl = window.location.search.substring(1);
  var splitted = longurl.split("&");


  for (i=0;i< splitted.length; i++) {
    var pair = splitted[i].split("=");

    var theKey = pair[0];
    var theValue = pair[1];

    if (theKey == key) {
      return theValue;
    }
  }

  // default is empty
  return "";

}

and here is the jquery script to select from the menu

$(function(){

  if( queryString("group_select") != "" ){
     $("#group_select").val( queryString("group_select") );
  }

});
Anwar Chandra
+1  A: 

If I understand correctly, if an user visits /rank/objects/?group_select=1 you want the "Group One" option to be selected by default?

Most people solve this using a server-side script. But if you want it is doable in Javascript as well.

I would start by extracting the "number" from location.search and then use jQuery's $("#group_select").val(number).

adamse