Search code examples
jquerystorageselectionlocal

How to save select option in localStorage with jQuery?


I am trying to save selected option in localStorage in HTML, so if you refresh page, the selection stays selected.

I have try this:

HTML:

<select id="edit">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

jQuery:

$(function() {
    $('#edit').change(function() {
        localStorage.setItem('todoData', this.innerHTML);
    });
    if(localStorage.getItem('todoData')){
        localStorage.getItem('todoData');
    }
});

But this seems not to work, any ideas, realy thanks for help...

Live Demo here: http://jsfiddle.net/nwk1g6vp/


Solution

  • Store and set the value, not the entire HTML of the select

    $(function() {
        $('#edit').change(function() {
            localStorage.setItem('todoData', this.value);
        });
        if(localStorage.getItem('todoData')){
            $('#edit').val(localStorage.getItem('todoData'));
        }
    });
    

    FIDDLE