根据数据生成表单

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>根据数据生成表单</title>

<script>
//定义一个数组承接里面的对象内容
//提取数组中的元素(这个元素是对象)
//用元素对象type属性判断这个对象是什么类型的标签
//再有对象拿到属性值给标签附上属性

//老套路
window.onload = function() {
var arr = [{
label: "用户名",
name: "username",
type: "text"
}, {
label: "密码",
name: "password",
type: "password"
}, {
label: "性别",
name: "gender",
type: "select",
value: ['男', '女']
}, {
label: '是否约么',
name: 'arrange',
type: 'radio',
value: ['约', '不约']
}, {
label: "爱好",
name: "hobby",
type: "checkbox",
value: ['篮球', '足球', '羽毛球', '兵乓球', '爬山', '购物', '旅游', '看美女']
}, {
label: '是否已婚',
name: 'married',
type: 'radio',
value: ['已婚', '未婚']
}, {
label: '简介',
name: 'resume',
type: 'textarea'
}];
//根据数据生成表单
//目地:根据数据生成html结构
//1)生成select下拉框 ==> <label>xx</label><select><option></option></select>
//2)checkbox/radio ==> <label>xx</label><label><input type = "checkbox/radio">篮球</label>
//3)其他情况 ==><label>xx</label><input type = "text">
//4)生成多行文本框 ==><label>xx</label><textarea></textarea>

//遍历数据,根据类型不同生成不同的html结构

for (var i = 0; i < arr.length; i++) {

var p = document.createElement("p");

//生成label标签
//每个表单元素都会有一个label标签,需要公共生成的不用放在判断条件执行体里面
var label = document.createElement("label");
//label包裹的内容
label.innerHTML = arr[i].label;
//添加label的for属性
label.for = arr[i].name;
//声明变量
var input;

//先判断特殊性
switch (arr[i].type) {
//select
case 'select':
input = document.createElement("select");
input.id = arr[i].name;
input.name = arr[i].name;

//生成下拉选项
for (var j = 0; j < arr[i].value.length; j++) {
var opt = document.createElement("option");
//option一定要添加value属性,这个是反馈到服务器的option内容
opt.value = arr[i].value[j];
//这个是option包裹的内容
opt.innerHTML = arr[i].value[j];
//把option放进select里面
input.appendChild(opt);
}
break;
//textarea
case 'textarea':
input = document.createElement("textarea");
input.id = arr[i].name;
input.name = arr[i].name;
break;

// checkbox/radio
case 'checkbox':
case 'radio':
//<label>xx</label><label><input type = "checkbox/radio">篮球</label>

//生成一个span标签,用来包裹所有的
input = document.createElement("span");

//循环value值,把所有的选项的生成html结构
for (var j = 0; j < arr[i].value.length; j++) {
var item = document.createElement("label");
var checkbox = document.createElement("input");

//设置类型
checkbox.type = arr[i].type;
checkbox.name = arr[i].name;
item.appendChild(checkbox); //<label><input type = "checkbox/radio"></label>

//设置文本节点
var txt = document.createTextNode(arr[i].value[j]);
item.appendChild(txt); //<label><input type = "checkbox/radio">篮球</label>
input.appendChild(item);
}
break;
// text/password
default:

input = document.createElement("input");
input.tpye = arr[i].type;
input.id = arr[i].name;
input.name = arr[i].name;
}
//把label 和 input标签放到p里面
p.appendChild(label);
p.appendChild(input);

//把p标签放到文档body里面
document.body.appendChild(p);

}

}
</script>
</head>

<body>
<form>

</form>
</body>

</html>

posted @ 2016-12-12 20:24  ~小白向前冲  阅读(684)  评论(0编辑  收藏  举报