开发者

Keep selectbox value after submit

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 f开发者_如何学编程unction 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>


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜