如何在jQuery JavaScript中从localstorage保存并获取表单状态

时间:2018-09-24 07:15:42

标签: javascript jquery node.js

我想在localstorage中保存表单状态,即我可以保存,但是

无法保存键入input的{​​{1}}

预期的输出::假设我在输入框中键入 doggy ,然后我想保留该 doggy ,以填入{{1} }。

这是codepen: https://codepen.io/anon/pen/mGYdKO?editors=1010

这是我尝试过的事情:

data
cloned
$(function(){
  $(document).on('click','#getstate',function(){
      var cloned = $('#wrapper-rrr').clone();
      console.log('cloned.html()',cloned.html());
      if($(this).is(':checked')){
         localStorage.setItem("form", JSON.stringify(cloned.html()));
      }else{
        var lastForm = JSON.parse(localStorage.getItem("form"));
         $('#displayAboveResult').html(lastForm);
      }
   });
})

请提前帮助我,谢谢!!!

2 个答案:

答案 0 :(得分:1)

在进行克隆以更改其DOM状态之前,只需触摸所有输入即可。

$(function(){
  $(document).on('click','#getstate',function(){
     $('input:text').each(function() {
         $(this).attr('value',           $(this).val());
     });
      var cloned = $('#wrapper-rrr').clone(true);
     console.log('cloned.html()',cloned.html());
      if($(this).is(':checked')){
         localStorage.setItem("form", JSON.stringify(cloned.html()));
      }else{
        var lastForm = JSON.parse(localStorage.getItem("form"));
         $('#displayAboveResult').html(lastForm);
      }
   });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper-rrr">
  <div class="form">
    <input type="text" placeholder="capture typed input into localstorage" value="">
    <input type="checkbox" id="getstate" value="">
  </div>
  <div id="displayAboveResult">
    <p>Empty in the begining</p>
  </div>
  
</div>

电笔示例: https://codepen.io/sumesh-tg/pen/wELGKO

我认为这会对您有所帮助。

答案 1 :(得分:0)

尝试一下:

My codePen example

<input type="text" placeholder="capture typed input into localstorage">为ID,例如#toBeRetain

$(function(){
  $(document).on('click','#getstate',function(){

      var cloned = $('#wrapper-rrr').clone(); 
      //console.log('cloned.html()',cloned.html());
      if($(this).is(':checked')){
         localStorage.setItem("form", JSON.stringify(cloned.html()));
      }else{
         var lastForm = JSON.parse(localStorage.getItem("form"));
         $('#displayAboveResult').html(lastForm);
         /*Set input value after clone*/
         $('#displayAboveResult #toBeRetain').val(localStorage['savedTxt']);
      }
  });
  /*Save input change to a localStorage variable*/
   $(document).on('change','#toBeRetain',function(){
      if(localStorage['savedTxt']){
         localStorage['savedTxt']=$('#toBeRetain').val();
      }else{
         localStorage.setItem("savedTxt",$('#toBeRetain').val());
      }           
  });
  //console.log(localStorage['savedTxt']);
})

当用户输入内容时,它的dom属性不会立即更新,因此无法克隆其值。

另一点是,我不确定您是否只需要复制一次或多次,如果是后一种情况,则需要使用$(this).parent()选择父div并更改选择器{{ 1}}到#