How to save select option in localStorage with jQu

2020-04-16 17:35发布

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/

2条回答
神经病院院长
2楼-- · 2020-04-16 18:13

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

查看更多
太酷不给撩
3楼-- · 2020-04-16 18:23

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

查看更多
登录 后发表回答