How do I get my selection to stick when I click save, and not have it default to its original state?
Example:
<select id="language" name="language"
<option value=""></option
<option value="One">One</option
<option value="Two">Two</option
<option value="Three">Three</option
</select>
So if I select "Two" option, then click save. It would default to the blank option.
Please Advise
I was expecting the drop down list to keep what you have selected when you save.
2
Answers
I don’t know how to complete it using only html. I don’t think that’s possible. You can use local storage in JS to save files. You can read here more about it here
when the user selects an element in the option block, you should save it in local storage when selecting the element, and when opening the page, load it from it and insert it into the option block.
There are several ways to achieve what you wanted and the best way is determined by your actual needs.
1. SUBMIT
Since you have a
select
tag and a SAVE button, it is quite possible that you have aform
that is submitted or a request is being sent in some different manner to the server, possibly AJAX. Yourselect
has aname
which is set tolanguage
, so, your request most probably has alanguage
parameter.So, your server gets the request and then responds with the same dropdown (among others). On your server-side you can check whether a
language
parameter was received and if so, whether it is equal to any of the options. If you use PHP, then you could have the following on your server:Of course, your might be using some other server-side language/technology, this is just an illustration of the idea you will need to apply.
2. Loading from the database or other storage
Since you have a SAVE button, you might want to save things on the database (or other server-side storage) when it is being clicked. If that’s the case, then you can modify the generation of your markup to mark the chosen option as
selected
based on the database and, if your form is posted, then first save it in your database. This would be an option that works across browsers for different users.3. Storing in localStorage or
sessionStorage
You can also specify a function that stores the chosen value in a storage, like
and then create a change event listener for your dropdown, like:
and, you can add a loadHandler to
body
, like: