繁体   English   中英

用户导航到其他页面并返回时不清除表单数据

[英]Not clearing form data when user navigates to other page and comes back

当用户导航到其他页面并在没有按下提交按钮的情况下返回时不清除表单数据

我过去使用store库构建了类似的东西 - https://github.com/nbubna/store

JSFiddle - https://jsfiddle.net/9dy54x2g/9/

索引.html

<html>
<body>
  <form id="formExample">
    <label for="name">Name</label>
    <input type="text" name="name" /><br />
    <label for="email">E-mail</label>
    <input type="text" name="email" />
    
    <button type="submit">
      Submit
    </button>
  </form>
  
  <script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>
  
  <script src="path/to/dist/store2.min.js"></script>
  
  <script src="script.js"></script>
 
</body>
</html>

Javascript (script.js):

$(function() {
  $('#formExample').submit(function(evt) {
    // Remove the localStorage details for the form
    store.remove("formDetails");
  });
  
  // Watch for changes to the inputs
  $('input').on('change', function(evt) {
    var form = document.querySelector('form');
    store.set('formDetails', JSON.stringify($(form).serializeArray()));
  });

  // Bringing the data values back from storage (on page refresh etc)
  var values = store.get('formDetails');
  if(values) {
    var existingFields = JSON.parse(values);
    $.each(existingFields, function(key, val) {
        $("input[name='" + val.name + "']").val(val.value);
    });
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM