下面我将介绍如何使用JavaScript和JSON数据动态创建包含输入框和复选框的HTML表单。
首先,我们需要一个JSON对象来描述表单的结构和字段:
const formConfig = {
formId: "dynamicForm",
fields: [
{
type: "text",
id: "username",
label: "用户名",
required: true,
placeholder: "请输入用户名"
},
{
type: "email",
id: "email",
label: "电子邮箱",
required: true
},
{
type: "checkbox",
id: "subscribe",
label: "订阅新闻",
checked: true
},
{
type: "checkbox-group",
id: "interests",
label: "兴趣爱好",
options: [
{ value: "sports", label: "体育" },
{ value: "music", label: "音乐" },
{ value: "reading", label: "阅读" }
]
}
],
submitText: "提交"
};
function createDynamicForm(config) {
const form = document.createElement('form');
form.id = config.formId;
config.fields.forEach(field => {
const fieldContainer = document.createElement('div');
fieldContainer.className = 'form-field';
if (field.type === 'checkbox-group') {
// 创建复选框组
const legend = document.createElement('legend');
legend.textContent = field.label;
fieldContainer.appendChild(legend);
field.options.forEach(option => {
const checkboxContainer = document.createElement('div');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = `${field.id}-${option.value}`;
checkbox.name = field.id;
checkbox.value = option.value;
const label = document.createElement('label');
label.htmlFor = checkbox.id;
label.textContent = option.label;
checkboxContainer.appendChild(checkbox);
checkboxContainer.appendChild(label);
fieldContainer.appendChild(checkboxContainer);
});
} else if (field.type === 'checkbox') {
// 创建单个复选框
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = field.id;
checkbox.name = field.id;
if (field.checked) checkbox.checked = true;
const label = document.createElement('label');
label.htmlFor = field.id;
label.textContent = field.label;
fieldContainer.appendChild(checkbox);
fieldContainer.appendChild(label);
} else {
// 创建文本/email等输入框
const label = document.createElement('label');
label.htmlFor = field.id;
label.textContent = field.label;
const input = document.createElement('input');
input.type = field.type;
input.id = field.id;
input.name = field.id;
if (field.required) input.required = true;
if (field.placeholder) input.placeholder = field.placeholder;
fieldContainer.appendChild(label);
fieldContainer.appendChild(input);
}
form.appendChild(fieldContainer);
});
// 添加提交按钮
const submitButton = document.createElement('button');
submitButton.type = 'submit';
submitButton.textContent = config.submitText;
form.appendChild(submitButton);
// 添加表单提交事件
form.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(form);
const formValues = Object.fromEntries(formData.entries());
// 处理复选框组的值
config.fields.forEach(field => {
if (field.type === 'checkbox-group') {
const checkboxes = form.querySelectorAll(`input[name="${field.id}"]:checked`);
formValues[field.id] = Array.from(checkboxes).map(cb => cb.value);
}
});
console.log('表单数据:', formValues);
// 这里可以添加表单提交逻辑
});
return form;
}
// 使用函数创建表单并添加到页面
document.addEventListener('DOMContentLoaded', function() {
const formContainer = document.getElementById('form-container');
const form = createDynamicForm(formConfig);
formContainer.appendChild(form);
});
可以扩展JSON配置来包含验证规则:
{
type: "text",
id: "password",
label: "密码",
validation: {
required: true,
minLength: 8,
pattern: "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$",
message: "密码必须至少8个字符,包含字母和数字"
}
}
然后在创建表单时添加验证逻辑。
可以根据其他字段的值显示/隐藏某些字段:
{
type: "select",
id: "userType",
label: "用户类型",
options: [
{ value: "personal", label: "个人" },
{ value: "business", label: "企业" }
],
dependentFields: {
"business": ["companyName", "taxId"]
}
}
对于更复杂的表单,可以考虑使用模板引擎如Handlebars或Vue/React等框架。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态表单生成</title>
<style>
.form-field {
margin-bottom: 15px;
}
label {
display: inline-block;
width: 120px;
}
legend {
font-weight: bold;
}
.checkbox-option {
margin-left: 120px;
margin-bottom: 5px;
}
</style>
</head>
<body>
<div id="form-container"></div>
<script>
// 这里放置上面的JSON配置和JavaScript代码
</script>
</body>
</html>
这种方法可以让你完全通过配置来创建复杂的表单,非常适合需要频繁更改表单结构或从后端动态加载表单配置的应用场景。