Skip to content

Instantly share code, notes, and snippets.

@zero-g
Created January 4, 2015 09:29
Show Gist options
  • Select an option

  • Save zero-g/9bc70b420c725e49b472 to your computer and use it in GitHub Desktop.

Select an option

Save zero-g/9bc70b420c725e49b472 to your computer and use it in GitHub Desktop.
表单输入数据进行验证接口的工具类
/**
* 表单输入数据进行验证接口的工具类
*/
var TestDataFormUtil = (function() {
var hasOwn = Object.prototype.hasOwnProperty;
var preIdStr = 'formUtil-';
var inputTemplate = '<p><span style="width:200px;display:inline-block;">{name}</span>: <input type="text" id="'+preIdStr+'{name}" style="width:300px"/></p>';
function createForm(container, object, callback) {
if(arguments.length < 2) {
object = container;
container = undefined;
}
var formHTML = '';
for(var key in object) {
if(hasOwn.call(object, key)) {
if(typeof object[key] === 'object') {
formHTML += arguments.callee(object[key])
} else {
formHTML += createInputValue(key);
}
}
}
if(container) {
var div = document.createElement('div');
div.style.border = '1px solid gray';
div.innerHTML = formHTML;
if(callback) {
var submitBtn = document.createElement('input');
submitBtn.type = 'button';
submitBtn.value = '设置';
submitBtn.onclick = function() {
var data = getFormValue(object);
callback(data);
}
div.appendChild(submitBtn);
}
container.appendChild(div);
} else {
return formHTML;
}
}
function getFormValue(object) {
var value = {};
for(var key in object) {
if(hasOwn.call(object, key)) {
if(typeof object[key] === 'object') {
value[key] = arguments.callee(object[key])
} else {
value[key] = getInputValue(key);
}
}
}
return value;
}
function getInputValue(name) {
return document.getElementById(preIdStr + name).value;
}
function createInputValue(name) {
return inputTemplate.replace(/{name}/g, function() {
return name;
});
}
return {
createForm: createForm //根据对象创建form表单。createForm(container, object, callback) 容器,对象,回调
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment