views:

24

answers:

1

On a website that I'm currently making I placed a selectbox were user's can sort a list of items displayed on the page. When they choose one, the page is being submitted and the selectbox value jumps back to the first default one. Now I want the selectbox to retain value after submitted.

Im working in XSLT, so I can't use PHP. Is there a Javascript function for this? or maybe a jQuery plugin/function?

Thanks

my form:

<form name="sort-form" action="{$root}/resorts/" method="get">
    <select name="filter" onChange="document.getElementById('sort-form').submit();">
        <option value="">Sort By...</option>
        <option value="recommended">Recommended</option>
        <option value="location">Location</option>
        <option value="prices-from">Low budget</option>
        <option value="prices-till">High budget</option>
    </select>
</form>
+1  A: 

You have two options:

  1. Submit form by AJAX.
  2. Save state to the Cookies.

I'll recommend using AJAX since it makes interfaces more interactive and saves internet traffic. To submit form you can use jQuery .post() method:

<script type="text/javascript"> 
   $(document).ready(function(){ 
    $("#sort-form").submit(function(){ 
        $.post("/your/url.php", 
            $("#sort-form").serialize(), 
            function(data){ 
                // optional callback 
           } 
       ); 
    }); 
  }); 

If this isn't an option (for example, page must be reloaded anyway), you have to set Cookies and then, after reloading, check them again. Example (using functions from here):

// on submit 
setCookie("select_value", document.getElementById('yourSelectId').value);
....
// on load
var sortSelect = document.getElementById('yourSelectId');
var val = getCookie("select_value");
for(index = 0; index < sortSelect.length; index++) {
if(sortSelect[index].value == val)
  sortSelect.selectedIndex = index;
}
Andrei
The ajax way didn't worked for me. I need to reload the page anyway after the submit so I tried the cookie option, but I can't seem to figure out how to set it up for my form. Can you give an example that matches my form?
Sandor
I cannot write exact code for your form without seeing PHP and XSLT parts. My advice is to check each part of your script step by step. Make it as simple as possible and then add needed complexity.
Andrei
I noticed some errors in your code just now. First, you pass to the `getElementById()` function form's name, not form's id. And second, I guess you need method `POST`, not `get` in form's declaration. I'm not sure this is the cause of an error, but these modifications will not break your code anyway.
Andrei