-1

I have a form that lets the user select an option from a <select> dropdown. When the form is opened again I'd like to show the dropdown set to the last value chosen by the user, which I've saved away. Is this possible with jQuery?

Thanks

Steve
  • 4,534
  • 9
  • 52
  • 110
  • Is the value stored in db? – Choco Oct 15 '14 at 06:23
  • If you want to do it in Javascript, you have to save it in a cookie. Usually this is done in the server script. When it's creating the menu, it makes the option in the database the default selected option. – Barmar Oct 15 '14 at 06:26

1 Answers1

2

You have basically two or three options.

  1. Save the value on server, e.g. in a database. Then, when displaying the <select>, you pre-select the option stored in the database. The jQuery part here could be sending an ajax request to your server to store the value.
  2. Save the value to the user i.e. to his cookies. See this question.
  3. If your web app uses sessions and it is sufficient that the option is remembered for one session, you can store the value to the session. However, sessions are, in effect, realized by either cookies or a server-side storage (or both).

To actually do the selecting:

HTML:

<select id="sel">
    <option value="o1">option 1</option>
    <option value="o2">option 2</option>
    ...
</select>

JS:

$(function () { // run a function when page is loaded (similar to onLoad event)
    var value = "o1"; // get the value to pre-select
    $("#sel").val(value);
});

See it in action here.

Community
  • 1
  • 1
zegkljan
  • 8,051
  • 5
  • 34
  • 49
  • The problem isn't storing and retrieving the value. I have the last value entered handy. I just want to preselect the select element to the saved value. – Steve Oct 15 '14 at 06:44
  • @Steve Check out my answer, I edited it to explain how to do the selecting stuff. – zegkljan Oct 15 '14 at 07:00