How to save data from a form with HTML5 Local Storage?

前端 未结 5 2015
我在风中等你
我在风中等你 2020-11-28 08:23

I have a form that makes logging into a website but not in mine and I want them to be saved form data in my web with HTML5 local storage. But not how. Any idea? My form is t

相关标签:
5条回答
  • 2020-11-28 08:44

    Here,Simple solution using JQUERY is like this..

    var username = $('#username').val();
    var password = $('#password').val();
    localStorage.setItem("username", username);
    localStorage.setItem("password", password);
    
    0 讨论(0)
  • 2020-11-28 08:52

    To save the data you have to use localStorage.setItem method and to get the data you have to use localStorage.getItem method.

    0 讨论(0)
  • 2020-11-28 08:53

    LocalStorage has a setItem method. You can use it like this:

    var inputEmail= document.getElementById("email");
    localStorage.setItem("email", inputEmail.value);
    

    When you want to get the value, you can do the following:

    var storedValue = localStorage.getItem("email");
    

    It is also possible to store the values on button click, like so:

    <button onclick="store()" type="button">StoreEmail</button>
    
    <script  type="text/javascript">
      function store(){
         var inputEmail= document.getElementById("email");
         localStorage.setItem("email", inputEmail.value);
        }
    </script>
    
    0 讨论(0)
  • 2020-11-28 08:54

    Here's a quick function that will store the value of an <input>, <textarea> etc in local storage, and restore it on page load.

    function persistInput(input)
    {
      var key = "input-" + input.id;
    
      var storedValue = localStorage.getItem(key);
    
      if (storedValue)
          input.value = storedValue;
    
      input.addEventListener('input', function ()
      {
          localStorage.setItem(key, input.value);
      });
    }
    

    Your input element must have an id specified that is unique amongst all usages of this function. It is this id that identifies the value in local storage.

    var inputElement = document.getElementById("name");
    
    persistInput(inputElement);
    

    Note that this method adds an event handler that is never removed. In most cases that won't be a problem, but you should consider whether it would be in your scenario.

    0 讨论(0)
  • 2020-11-28 08:57

    You can save form data in localstorage applying form validation using javascript. Just read this easy article https://xeeratech.com/form-validation-in-javascript-and-store-form-data-in-localstorage/

    0 讨论(0)
提交回复
热议问题