1

Here I am posting my problem statement.

User select option from drop down. Selected value appears on page. But, when user refresh the page then that selected value disappears from page.

I need that that value should be what I selected before refresh the page. Is this possible using js/jquery.

Please guide me how I can achieve this!

Regards

S Singh
  • 1,403
  • 9
  • 31
  • 47
  • Is there a server side component to your site (this may be a better place to persist this if there is)? – Paddy Jul 06 '12 at 08:29
  • @Paddy that might be a bit heavy, wouldn't it? Would you recommend an account-like setup? – DZittersteyn Jul 06 '12 at 08:33
  • 1
    You can use localStorage or sessionStorage. http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – Pramod Jul 06 '12 at 08:36
  • @DZittersteyn - was just a question. If there was already a server side method, then it may have been more appropriate, but if not, then cookies etc. is what you get. – Paddy Jul 06 '12 at 08:48
  • @Pramod sessionStorage works for me! thanks!! – S Singh Jul 06 '12 at 11:28

3 Answers3

3

You have several solutions to do this.

  1. Every time the user selects an option, send a http request to the server with the selected option. When the user refreshes the page, the jsp will use the collected info to pre-select the option. A common $.get in jQuery will do the trick client-side.
  2. Set up a cookie with the selected option. When the page is refreshed, get the cookie value and use it to pre-select the option. You don't need jQuery to do this, but it may help.
  3. If the browser supports it, use localStorage instead of cookies. It's a client-side only solution, so the info won't be sent to the server.
  4. Set up the hash of the URL to store the option:

    location.replace("#option=" + val);

    You can retrieve the value when the page is refreshed using location.hash.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
0

You have a couple of options here:

You can set a cookie using jQuery which saves the previous state. A nice tutorial can be found here: http://www.electrictoolbox.com/jquery-cookies/

you could also encode the options in the url with a query string. Some info about that can be found on wikipedia: http://en.wikipedia.org/wiki/Query_string

Which of the two you want is up to you, cookies are the way to go if you want the settings to persist if the user leaves the page and visits another time, the query string is more useful to prevent refreshing from clearing your settings.

DZittersteyn
  • 628
  • 3
  • 8
0

Using the cookie plugin (http://plugins.jquery.com/project/Cookie):

$("#MyList").change(function() {
    //Set a cookie with selected value on change.
    $.cookie("SelectedItem", $(this).val());
});

$(document).load(function() {
    //On load, set the selected item from the cookie.
    $("#MyList").val($.cookie("example")); 
});
Paddy
  • 33,309
  • 15
  • 79
  • 114