1.表单取值/赋值公共方法
//表单序列化:文本框的name字段和数据源一致<form id="myForm" onsubmit="return false;">
function getFormJsonData(formId) {
var fields = $("#" + formId).serializeArray();
var f = {};
$.each(fields, function (index, field) {
f[field.name] = field.value;
})
return f;
}
//表单填充数据:文本框的name字段和数据源一致
function setFormJsonData(data) {
if (data) {
for (var i in data) {
////console.log(i + ":" + data.JingShenBing[i]);
if (document.getElementsByName(i + "").length > 0) {
document.getElementsByName(i + "")[0].value = data[i];
} }
} }
2.调用
<form id="form2" name="form2" onsubmit="return false">
<input name="name" />
<input name="age" />
<input value="提交" type="button" onclick="getFormData()" />
<input value="setValue" type="button" onclick="setFormData()" />
</form>
<script>function getFormData() {
var data = getFormJsonData("form2");
data.id = 1; //追加数据
var data1={sex:'0'};
Object.assign(data1, data); //copy复制对象
console.log(data1);
}
function setFormData() {
var data = {"name":"jay","age":"22"};
setFormJsonData(data);
}
</script>
3.生成下拉框
//调用:createSelect("url","Name","Id","selectId",-1, [{"Name":"全部","Id":"-1"}],null);
//参数:数据源地址,显示字段,取值字段,下拉框id,默认选中值,开头追加数据,成功回调
function createSelect(url,displayField,valueField,selectId, defaultValue, insertDataAtFirst, cb) {
try {
var obj = document.getElementById(selectId);
//var url = obj.getAttribute("attr-url");
//var displayField = obj.getAttribute("attr-displayField");
//var valueField = obj.getAttribute("attr-valueField"); ////alert(displayField);
var str = "";
if (insertDataAtFirst) {
for (var i = 0; i < insertDataAtFirst.length; i++) {
var item = insertDataAtFirst[i];
////console.log("option:", item[displayField]);
str += "<option value='" + item[valueField] + "' >" + item[displayField] + "</option>";
}
}
ajax(url, null, function (data) {
if (data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
////console.log("option:", item[displayField]);
str += "<option value='" + item[valueField] + "'>" + item[displayField] + "</option>";
} }
obj.innerHTML = str;
if (defaultValue != null && defaultValue != "") {
obj.value = defaultValue;
} if (cb) {
cb(obj.value);
}
});
} catch (e) {
console.log('%c createSelect error:', 'background:white;color:red',e);
} }
调用:
//参数:数据源地址,显示字段,取值字段,下拉框id,默认选中值,开头追加数据,成功回调
createSelect("api/Dict/GetProvinces", "Name", "Id", "selProvince", -1, {Id:-1,Name:"请选择"}, null);
968AF3B3-37D5-4689-ACAB-9BB3D0F6BAD4 From:http://www.cnblogs.com/xuejianxiyang/p/8416527.html