【问题标题】:How to get data from form to javascript and redirect to another page?如何从表单获取数据到 javascript 并重定向到另一个页面?
【发布时间】:2013-12-17 06:29:03
【问题描述】:

我有一个带有名字、姓氏等的 html5 表单。我使用表单的原因是用户必须填写所有内容,因为我使用的是required。我想将所有数据保存在 localStorage 中,因为我需要将数据移动到 JavaScript。

在将用户重定向到另一个页面时按下submit 按钮时如何访问JavaScript 中的数据?

这是代码:

HTML5

<form id="TheForm" method="post">
   <input type="text" id="Name" placeholder="*Förnamn" required >
   <input type="text" id="Surname" placeholder="*Efternamn" required >
   <input type="email" id="FirstEmail" placeholder="*e-postadress" autocomplete="on" required >
   <input type="email" id="SecondEmail" placeholder="*Verifiera e-postadress" autocomplete="off" required >
   <input type="text" id="Address" placeholder="*Adress" required >
   <input type="submit" id="Submit" onclick="function()" value="Skicka">
</form> 

【问题讨论】:

  • 可以选择 jQuery 吗?如果是,则序列化表单数据,然后存储。
  • 我猜可以工作..还有其他方式吗?
  • 其实不行,不行
  • 使用 Vanilla JS,您可以直接访问 DOM 元素。例如,var name = document.getElementById("Name").value; 会将 Name 的值存储在一个名为“name”的 JS 变量中。
  • 只有在所有字段都填满时才会调用它吗?我应该将功能放在按钮的 onclick="" 和表单标签中的下一页吗?

标签: javascript html forms local-storage


【解决方案1】:
var submit = function () {
    window.localStorage.name = document.getElementById('Name').value;

    // Save all the other fields
    // You either return a non-false value here and let the form submit
    // Or you return false and do a window.location change 
};

window.onload = function () {
    var form = document.getElementById('TheForm');

    if (form.attachEvent) {
        form.attachEvent('submit', submit);
    } else {
        form.addEventListener('submit', submit);
    }
}

【讨论】:

  • 我应该给函数命名吗?
  • 哈哈那个回复,我猜不是 :D 我的意思是 var submit = functon () 和 windows.onload = function()
  • 顺便说一句,控制台出现错误:无法读取 null 的属性“attachEvent”。它显示了 form.attachEvent 行
  • 你的表单ID是什么?
【解决方案2】:

试试这个

Java 脚本

function storeDetails() {
    if(typeof(Storage)!=="undefined") {
       localStorage.setItem('name', document.getElementById('Name').value));                              
       //code to store other values will go here
    } else {
        alert('Your browser do not support local storage');
    }
}

HTML

<form id="TheForm" method="post" onsubmit="javascript:storeDetails();" action=" ">
   <input type="text" id="Name" placeholder="*Förnamn" required >
   <input type="text" id="Surname" placeholder="*Efternamn" required >
   <input type="email" id="FirstEmail" placeholder="*e-postadress" autocomplete="on" required >
   <input type="email" id="SecondEmail" placeholder="*Verifiera e-postadress" autocomplete="off" required >
   <input type="text" id="Address" placeholder="*Adress" required >
   <input type="submit" id="Submit" onclick="function()" value="Skicka">
</form> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-28
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    相关资源
    最近更新 更多