清空表单数据 表单填充数据 js 操作表单数据 将Form的数据转化成Javascript的Json对象
/**
* @brief 表单内容自动填充
*/
var autoComplete = function(formObj,data)
{
var _self = this;
_self.data = (typeof(data) == 'object') ? data : (data.length ? eval('(' + data + ')') : '');
_self.formObj = formObj;
/**
* @brief 构造函数
*/
this.__construct = function()
{
if(typeof(_self.data) != 'object')
{
return false;
}
_self.init();
}
/**
* @brief 填充内容
*/
_self.init = function(data)
{
(typeof(data) == 'undefined') && (data = _self.data);
for(var i in data)
{
if(typeof(data[i]) == 'object')
{
_self.init(data[i]);
}
else
{
var obj = $('[name="' + i + '"]');
var tag_name = '';
if(obj[0])
{
tag_name = obj[0].tagName.toLowerCase();
}
var tag_type = obj.attr('type');
switch(tag_type)
{
case 'radio':
case 'checkbox':
obj.each(function(){
if($(this).val() == data[i])
{
$(this).prop('checked',true);
}
else
{
$(this).prop('checked',false);
}
});
break;
case 'img':
obj.attr('src',data[i]);
break;
default:
obj.val(data[i].toString().replace(/amp;/g,''));
break;
}
}
}
}
_self.__construct();
}
//将Form的数据转化成Javascript的Json对象
//Jquery的serializeArray 方法已经可以实现将Form的数据序列化为一个数组,只要稍微在这个方法的基础上做些修改即可。
//方法1:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
}
//方法2:
var data = {};
$("form").serializeArray().map(function(x){data[x.name] = x.value;});
//方法3
var d={};$(form).find('input,select').each(function(){d[this.name]=this.value});console.log(d);
//方法4
var d = {};
var t = $('form').serializeArray();
$.each(t, function() {
d[this.name] = this.value;
});
alert(JSON.stringify(d));
//清除所有的表单数据
//可能针对不同的表单形式,你需要调用不同类型的清楚方法,不过使用下面这个现成方法,绝对能让你省不少功夫。
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1; // 0.为第一项 -1.什么都不选择
});
};