You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript将注册表单数据存入以firstname为键的父对象

实现注册表单数据存储为指定格式的对象

核心思路

  • 读取表单中firstname、lastname、email、password的输入值
  • 以firstname的内容作为父对象的键,将所有字段信息封装为对应的子对象
  • 可选择将对象存储到本地存储或作为变量使用

HTML 表单示例

<form id="registrationForm">
  <input type="text" id="firstname" placeholder="First Name" required>
  <input type="text" id="lastname" placeholder="Last Name" required>
  <input type="email" id="email" placeholder="Email" required>
  <input type="password" id="password" placeholder="Password" required>
  <button type="submit">Register</button>
</form>

JavaScript 实现代码

// 获取表单元素
const form = document.getElementById('registrationForm');

// 监听表单提交事件
form.addEventListener('submit', function(e) {
  e.preventDefault(); // 阻止默认提交行为

  // 读取输入字段值
  const firstname = document.getElementById('firstname').value.trim();
  const lastname = document.getElementById('lastname').value.trim();
  const email = document.getElementById('email').value.trim();
  const password = document.getElementById('password').value;

  // 构造目标格式的对象
  const userData = {
    [firstname]: {
      firstname: firstname,
      lastname: lastname,
      email: email,
      password: password
    }
  };

  // 示例:存储到localStorage
  localStorage.setItem('registeredUsers', JSON.stringify(userData));

  // 若需累积多个用户,可合并现有数据
  // let existingUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
  // existingUsers = {...existingUsers, ...userData};
  // localStorage.setItem('registeredUsers', JSON.stringify(existingUsers));

  console.log('存储的数据:', userData);
  alert('注册完成');
  form.reset(); // 重置表单
});

重要提示

  • 密码安全:实际项目中禁止明文存储密码,必须使用哈希算法(如bcrypt)加密后再保存
  • 输入验证:建议添加邮箱格式检查、密码强度校验等逻辑,提升数据有效性

内容的提问来源于stack exchange,提问作者Kondaveti Charan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:50:05