Save and load input values using local storage?

后端 未结 2 907
天涯浪人
天涯浪人 2020-12-13 17:02

I\'m trying to store via local storage all form field values (under the input id) like so localStorage.setItem(\"input id\", fieldvalue); when a user clicks the

2条回答
  •  醉话见心
    2020-12-13 17:03

    If you want to rely on jQuery this can help you:

    $('#save').on('click', function(){
    
        $('input[type="text"]').each(function(){    
            var id = $(this).attr('id');
            var value = $(this).val();
           localStorage.setItem(id, value);
    
        });   
    });
    
    $('#load').on('click', function(){
        $('input[type="text"]').each(function(){    
            var id = $(this).attr('id');
            var value = localStorage.getItem(id);
    
            $(this).val(value);
    
        }); 
    });
    

    I would recommend to avoid inline-js, so I updated to code to use .on() for attaching the click-handler to the two buttons.

    Demo

    Reference:

    .each()

提交回复
热议问题