Js 表单与对象相互绑定

function GetFormData(formId) {
//获取表单数据
var postData = $("#" + formId).serializeArray();
var data = [];
for (var i = 0; i < postData.length; i++) {
var IsAdd = true;
for (var j = 0; j < data.length; j++) {

if (data[j].name == postData[i].name) {
data[j].value += "%&" + postData[i].value//重复键用"%&"隔开
IsAdd = false;
break;
}
}
if (IsAdd) {
data.push(postData[i]);
}
}
return data;
}
function BindForm(formId, data) {//绑定数据给表单

for (items in data) {
var dd = $("#" + formId + " [name^='" + items + "']");
if (dd != null) {
var ty = dd.attr("type");
if (ty != null && ty == "radio") {
dd.removeAttr("CHECKED");
$("[name=" + items + "][value=" + data[items] + "]").attr("checked", true);

} else if (ty != null && ty == "checkbox") {
dd.removeAttr("CHECKED");
var strdata = data[items].split("%&");
for (var k = 0; k < strdata.length; k++) {
$("[name=" + items + "][value=" + strdata[k] + "]").attr("checked", true);

}

} else {
dd.val(data[items]);
}
}
}

}

posted @ 2014-09-17 11:42  文艺流浪汉  阅读(541)  评论(0编辑  收藏  举报