How to save select option in localStorage with jQuery?

人走茶凉 提交于 2019-12-02 09:47:20

问题


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/


回答1:


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




回答2:


Use value property or .val() function

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

Example



来源:https://stackoverflow.com/questions/28265744/how-to-save-select-option-in-localstorage-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!