【问题标题】:Store form in localstorage, retrieve it later for submit将表单存储在本地存储中,稍后检索它以提交
【发布时间】:2022-01-21 09:30:33
【问题描述】:

在 wordpress 网站中,我希望当有人填写产品表单(选择属性等)并单击立即购买时,如果未登录,则将他重定向到登录表单。成功登录后,我想从localstorage获取提交的表单内容,填写表单,然后自动提交表单。

这可能吗?

我发现我可以像这样存储提交的表单(但是如何自动重新填写表单?):

$(document).ready(function()    {  
    $('form').submit(function(e) {    
        e.preventDefault();
        var formFields = $(this).serialize();
        localStorage.setItem('myForm', formFields);    
        //data = localStorage.getItem('myForm');  //retrieve it later
     });
});

【问题讨论】:

  • 请出示您的 HTML 代码。它们需要自动填充,为此我们需要代码

标签: javascript jquery forms local-storage


【解决方案1】:

您应该能够从 localStorage 检索数据,使用 DOM 选择器获取表单字段并使用 localStorage 中的数据填充它们的值。

在 vanilla JS 中,您可能可以执行以下操作:

document.addEventListener('load', () => {
  // check if user is logged in according to your usecase
  if(isLoggedIn()) {
    try {
      const formData = JSON.parse(localStorage.getItem('myForm'));
      // get input fields. If you have some unique id associated to them, you can use document.querySelector(`#${inputId}`);
      const inputFields = document.querySelectorAll('input');
      for(let i = 0; i<inputFields.length; i++) {
         const inputId = inputFields[i].getAttribute('data-id');
         // fallback to empty string in case it is not found in localStorage object
         inputFields[i].value = formData[inputId] || '';
      }
    } catch(e) {
      // handle error
    }

    // Now you have the form input fields pre-filled, add custom logic from here .. 
  }

})

/* 
  --- Sample DOM ----
  <input data-id="name" />
  <input data-id="city" />


  ---- Form fields saved in localStorage ---
  { name : 'Naruto', city: 'Leaf Village' }
*/

【讨论】:

  • 我的问题是我不想对表单字段进行硬编码,因为它可能会有所不同。这可能吗?
  • @netdev 我相信这是可能的,但是在重定向到登录页面之前,您仍然需要将输入字段识别为用户填写的值。所以我想说如果你有一些逻辑来动态识别它们会很好。
  • 但我正在考虑将 POST 字段保存在本地存储中,然后(登录后)提交表单,其中包含从本地存储中检索到的 POST 字段
  • @netdev 我想你有多个输入字段。您为它们保存值,这很容易。但是当用户返回时,您希望将值放回正确的输入字段。问题是您如何将输入字段识别为用户输入的值?例如。您有 5 个输入字段,每个字段都有一些值。现在我们必须将这 5 个值映射回正确的 5 个输入字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 2012-05-05
  • 2016-03-31
  • 1970-01-01
  • 2015-06-12
  • 2017-03-08
  • 2021-09-10
相关资源
最近更新 更多