3

I have got the <select> element. And if I'm choosing for something, I would like to change URL by my value in <select> and set selected=selected.

Try something like this (jQuery):

  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type = "text/javascript">

  $(document).ready(function() {
      $('#my-select').bind('change', function () { 
          var url = $(this).val(); 
          if (url != '') { 
              window.location = url;
              $('#my-select').find("option[value='"+url+"']").attr("selected", "selected");
          }
          return false;
      });
  });

  </script>


<select id="my-select" name="category">
     <option selected> Please select... </option>
     <option value="index.php?page=category&s=something1"> something1 </option> 
     <option value="index.php?page=category&s=something2"> something2 </option> 
</select>

URL is changed, but attribute selected is not set.

I searched everywhere for about an hour, but never a proper example. Excuse me for my worse English.

What is going wrong? How to solve that?

RePRO
  • 265
  • 6
  • 18
  • 4
    Changing the location redirects you to a new page. The code after the `window.location =` essentially doesn't run. – JaredPar Mar 13 '12 at 23:38
  • I guess you want to change `my-select` in the new page, am I right? If so, this code should be in the DOM ready of the page. – gdoron Mar 13 '12 at 23:40
  • @JaredPar is right, I didn't notice that. If you want the select box to maintain the selected value, you would need to do that in the page to which you navigated. – Scorpion-Prince Mar 13 '12 at 23:42
  • No, at self page. I'm changing the values of select - it causes change the URL, but select is still on the same page. ;-) And I need that selected=selected. ;-) – RePRO Mar 13 '12 at 23:44

4 Answers4

4

Try something like this (untested).

  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type = "text/javascript">

  $(document).ready(function() {
      $('#my-select').val(document.location);

      $('#my-select').bind('change', function () { 
          var url = $(this).val(); 
          if (url != '') { 
              window.location = url;

          }
          return false;
      });
  });

  </script>
Valamas
  • 24,169
  • 25
  • 107
  • 177
  • `Redirect` works, but `selected=selected` doesn't works. Thank you for code... Any other suggestions? – RePRO Mar 13 '12 at 23:50
  • 1
    http://stackoverflow.com/questions/292615/how-can-i-set-the-value-of-a-dropdownlist-using-jquery – Valamas Mar 14 '12 at 00:03
  • Yes, but in my question is important redirecting the URL. ;-) Without redirecting it will be work, but I have got redirecting. I will try what wrote Lix. – RePRO Mar 14 '12 at 00:08
1

Since I've learned so much from stackoverflow (including this post)...I'm posting my solution to this problem. This code is tested and is working. Doing something like this comes in handy when you are building html pages with some kind of server-side scripting like PHP.

<script type = "text/javascript">
            jQuery(document).ready(function() {
              jQuery('#service-select').val(window.location.href); //set selected element of dropdown to be same as current page's address  
              //console.log(window.location.href); do this and check the console to see the exact value of this property
                jQuery('#service-select').bind('change', function () { 
                    var url = jQuery(this).val(); 
                    if (url != '') {
                        window.location = url; // redirect
                    }

                    return false;
                });
            });
</script>

Some important things to remember here - I'm using jQuery() instead of $() because my solution was written for WordPress and $() doesn't play nice with it :)

Since I'm using WP, I'm already calling in the jQuery libraries elsewhere. Just make sure you have the call to it somewhere in your markup.

Doing:

$('#my-select').val(document.location);

As proposed did not work for me.

I suggest using console.log() and printing out the exact value of document.location, window.location, etc. so that you can match it in your options elements.

In my case I was missing a trailing / in my HTML and it did not work as there is no match between http://example.com/beans and http://example.com/beans/

Anyways, hope this helps.

Tate Harmann
  • 101
  • 1
  • 3
0

it's easy, just after you redirect execute next code when document is loaded.

$('#my-select').val(your_url);

so basically I don't know what kind of values are in your select but if they are pathNames then for var your_url use

document.location.pathname

otherwise

document.location
Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
0

You could redirect your users with a GET parameter to be read on the next page load.

This JavaScript function (taken from here) returns all the GET parameters :

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

So what you would want to do is this :

$('#my-select').bind('change', function () { 
  var selectionValue = $(this).val(); 
  if (selectionValue != ''){
    var getParams = getUrlVars();
    // Next line is deciding whether to use a '?' or a '&' 
    // depending if there were already GET parameters in the URL
    var symbolToUse = (getParams? '&' : '?' );

    // Remove previous instances of "selected" in the URL.
    var url = window.location.href.replace(/[&|?]selected=\d+/g,"");
    window.location.href = url + symbolToUse + "selected="+selectionValue;
  }
)}

When the user makes a change to the select element, its value will be extracted and appended to the url.

https://repro.com/index.php?page=category&s=something2?selected=4
Here we can see that the user has wisely chosen eggs.

Then you include the call to the getURLVars() function on your document.ready callback -

$(document).ready(function() {
  var getParams = getUrlVars();
  if (getParams){
     // Here we make the selection of the <select> by setting its value
     // to the same as that of the <option> that was chosen and 
     // placed in the URL as a GET parameter. 
     $('#my-select').val(getParams.selected);
  }
  ...
)}

and now your select element will have the value that the user clicked on - provided that the selected parameter contains a valid value.

This also requires that your <option> tags contain value attributes with only the "id" of the option; No need for the whole URL as we are using the existing one -

<select id="my-select">
    <option value="1">FOO</option>
    <option value="2">BAR</option>
    <option value="3">SPAM</option>
    <option value="4">EGGS</option>
</select>
Lix
  • 47,311
  • 12
  • 103
  • 131
  • But I need set the selected value. I couldn't see that in code. – RePRO Mar 14 '12 at 00:16
  • You don't have to use that property - you can just set the `val()` of the ` – Lix Mar 14 '12 at 00:18
  • I've added some comments to my code to show where I am setting the "selected" value. Although I am not using the `selected=selected` syntax. – Lix Mar 14 '12 at 00:25
  • See **MY** edits - I made some improvements from the original post. – Lix Mar 14 '12 at 00:25
  • See. But I edited my post (look at my select). Your code makes me this URL: **index.php?selected=index.php?page=category&s=something1** – RePRO Mar 14 '12 at 00:44
  • How does the values selected gets me the number? But something is still going wrong... – RePRO Mar 14 '12 at 00:53
  • Please read my post **carefully** - I have stated that your value attribute in the ` – Lix Mar 14 '12 at 07:53