简体   繁体   中英

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

Not clearing form data when user navigates to other page and comes back without pressing submit button

I've built something similar in the past using the store library - https://github.com/nbubna/store

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

Index.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);
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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