Is There a way to have the selected option be the default value upon refreshing?

html, javascript, jquery

Solution

I think local storage can help to you. So for example:

<select id="options">
<option value="0">Apple</option> 
<option value="1">Orange</option> 
<option value="2">Mango</option></select>

Javascript

$("#options").on("change", function(){
    var val = $(this).val();
    // save to local
    if(window.localStorage){
        window.localStorage.setItem("#options-val", val);
    }
});

if(window.localStorage){
    var item = window.localStorage.getItem("#options-val");
    if(item) $("#options").val(item);
}

And see demo

All your js code must be inside $(document).ready()

After run code on demo, try to reload page and you will see the result!

Problem

I have this problem today, I wanted my selected option would be the default value upon refresh of my page. For example I have this: ``` <select id="options"> <option value="0">Apple</option> <option value="1">Orange</option> <option value="2">Mango</option></select> ``` the default on my UI is Apple, so what I want is when I clicked Orange option it will be the default value when I refresh the page. Is there a way to do this? Thanks

Original source