-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathserializeForm.js
More file actions
60 lines (51 loc) · 1.62 KB
/
serializeForm.js
File metadata and controls
60 lines (51 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* serializeForm
* https://github.com/danheberden/serializeForm
*
* Copyright (c) 2012 Dan Heberden
* Licensed under the MIT, GPL licenses.
*/
(function( $ ){
$.fn.serializeForm = function(fn) {
// don't do anything if we didn't get any elements
if ( this.length < 1) {
return false;
}
var data = {};
var lookup = data; //current reference of data
var selector = ':input[type!="checkbox"][type!="radio"], input:checked';
var parse = function() {
// data[a][b] becomes [ data, a, b ]
var named = this.name.replace(/\[([^\]]+)?\]/g, ',$1').split(',');
var cap = named.length - 1;
var $el = $( this );
var val;
// Ensure that only elements with valid `name` properties will be serialized
if ( named[ 0 ] ) {
for ( var i = 0; i < cap; i++ ) {
// move down the tree - create objects or array if necessary
lookup = lookup[ named[i] ] = lookup[ named[i] ] ||
( named[ i + 1 ] === "" ? [] : {} );
}
// at the end, push or assign the value
if ( lookup.length !== undefined ) {
val = $el.val();
if($.isFunction(fn)){
val = fn(val);
}
lookup.push( val );
}else {
lookup[ named[ cap ] ] = $el.val();
}
// assign the reference back to root
lookup = data;
}
};
// first, check for elements passed into this function
this.filter( selector ).each( parse );
// then parse possible child elements
this.find( selector ).each( parse );
// return data
return data;
};
}( jQuery ));