Save and load input values using local storage?

后端 未结 2 901
天涯浪人
天涯浪人 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()

    0 讨论(0)
  • 2020-12-13 17:21
       Replace Html Code And Script File 
       <form method='post' id='myform'>
        <input type="text" id="meta_title" name="seo_meta_title"> 
        <input type="text" id="meta_description" name="seo_meta_description"> 
        <input type="text" id="header" name="header"> 
    
        <!-- Submit form-->
          <input type="submit" id="save" value="Create">
    
        <!-- buttons-->
          <button onclick="save()">save</button>
          <button onclick="load()">load</button>
        </form>
        <script>
        $('#save').on('click', function(){
           var post_vars = $('#myform').serializeArray();
           localStorage.setItem(id, post_vars);
        });
        </script>
    
    0 讨论(0)
提交回复
热议问题