HTML DOM 提交表单
2025-04-24
18
参考资料
HTML DOM 表单提交
详细介绍
HTML DOM (文档对象模型) 提供了通过 JavaScript 操作 HTML 表单的方法。表单提交是 Web 开发中常见的交互方式,允许用户向服务器发送数据。
主要标签
<form>
- 定义表单容器action
: 指定提交目标 URLmethod
: 提交方法 (GET/POST)enctype
: 编码类型 (application/x-www-form-urlencoded, multipart/form-data)表单控件:
<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 操作、验证和样式扩展。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。