参考资料

  1. HTML DOM 访问
  2. HTML DOM 获取第一个链接ID的实例
  3. HTML DOM 返回一个表单中元素的数量 实例
  4. HTML DOM 当点击完button不可用 实例
  5. HTML DOM弹出下拉列表中被选中的选项的索引
  6. HTML DOM 返回图像映射的某个区域的pathname 实例
  7. HTML DOM一个单元格的innerHTML
  8. HTML DOM 修改 HTML 内容

HTML DOM 提交表单

HTML DOM 表单提交

详细介绍

HTML DOM (文档对象模型) 提供了通过 JavaScript 操作 HTML 表单的方法。表单提交是 Web 开发中常见的交互方式,允许用户向服务器发送数据。

主要标签

  1. <form> - 定义表单容器

    • action: 指定提交目标 URL

    • method: 提交方法 (GET/POST)

    • enctype: 编码类型 (application/x-www-form-urlencoded, multipart/form-data)

  2. 表单控件:

    • <input> (text, password, radio, checkbox, submit, etc.)

    • <select><option>

    • <textarea>

    • <button>

基本用法

<form id="myForm" action="/submit" method="post">
  <input type="text" name="username">
  <input type="password" name="password">
  <button type="submit">提交</button>
</form>

DOM 操作实例

1. 通过 JavaScript 提交表单

document.getElementById("myForm").submit();

2. 阻止默认提交行为

document.getElementById("myForm").addEventListener("submit", function(event) {
  event.preventDefault(); // 阻止表单默认提交
  // 自定义处理逻辑
});

3. 获取表单数据

const formData = new FormData(document.getElementById("myForm"));
// 遍历数据
for (let [key, value] of formData.entries()) {
  console.log(key, value);
}

4. AJAX 表单提交

document.getElementById("myForm").addEventListener("submit", function(e) {
  e.preventDefault();
  const formData = new FormData(this);
  
  fetch(this.action, {
    method: this.method,
    body: formData
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
});

功能扩展

表单验证

function validateForm() {
  const username = document.forms["myForm"]["username"].value;
  if (username == "") {
    alert("用户名不能为空");
    return false;
  }
  return true;
}

动态添加表单字段

function addField() {
  const newField = document.createElement("input");
  newField.type = "text";
  newField.name = "newField";
  document.getElementById("myForm").appendChild(newField);
}

CSS 扩展

基础样式

form {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 5px;
}

input, select, textarea {
  width: 100%;
  padding: 10px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

button[type="submit"] {
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: 100%;
}

button[type="submit"]:hover {
  background-color: #45a049;
}

验证样式

input:invalid {
  border-color: #ff0000;
}

.error-message {
  color: #ff0000;
  font-size: 0.8em;
  margin-top: -5px;
  margin-bottom: 10px;
}

响应式布局

@media screen and (max-width: 600px) {
  form {
    width: 90%;
    padding: 10px;
  }
}

这些内容涵盖了 HTML DOM 表单提交的主要方面,包括基本用法、JavaScript 操作、验证和样式扩展。