Last active
January 25, 2018 07:20
-
-
Save shikaiwen/6bfa7e0626b8962877d1390338aa4a26 to your computer and use it in GitHub Desktop.
javascript jquery form helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
kaiwen | |
表单工具类集合,方法可以在此添加 | |
**/ | |
(function($){ | |
var methods = { | |
/** | |
* 将表单元素序列化为json数据,如果有多个名称相同的元素,则变成 name:[] (数组形式存储) | |
*/ | |
getAsJson : function(){ | |
var form = $(this); | |
var data = {}; | |
$(form).serializeArray().map(function(item){ | |
if( data[item.name] ){ | |
if( typeof(data[item.name]) === "string"){ | |
//只有一个值时,创建数组 | |
var valueArr = []; | |
valueArr.push(data[item.name]); //previous value | |
valueArr.push(item.name); // current value | |
data[item.name] = valueArr; | |
}else if ( typeof(data[item.name]) === "array" ) { | |
data[item.name].push(item.name); | |
} | |
}else { | |
data[item.name] = item.value; | |
} | |
}); | |
return data; | |
}, | |
} | |
$.fn.formHelper = function(method){ | |
if (methods[method]) { | |
return methods[method].apply(this,Array.prototype.slice.call(arguments,1)); | |
} else if (typeof method === 'object' || !method) { | |
return methods.init.apply(this,arguments); | |
}else{ | |
console.log(method + ' does not exist'); | |
} | |
} | |
})($); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment