-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathjquery.deserialize.js
More file actions
69 lines (59 loc) · 1.85 KB
/
jquery.deserialize.js
File metadata and controls
69 lines (59 loc) · 1.85 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
61
62
63
64
65
66
67
68
69
/**
* @author Maxim Vasiliev
* Date: 21.01.2010
* Time: 14:00
*/
(function($)
{
/**
* jQuery.deserialize plugin
* Fills elements in selected containers with data extracted from URLencoded string
* @param data URLencoded data
* @param clearForm if true form will be cleared prior to deserialization
*/
$.fn.deserialize = function(data, clearForm)
{
this.each(function(){
deserialize(this, data, !!clearForm);
});
};
/**
* Fills specified form with data extracted from string
* @param element form to fill
* @param data URLencoded data
* @param clearForm if true form will be cleared prior to deserialization
*/
function deserialize(element, data, clearForm)
{
var splits = decodeURIComponent(data).split('&'),
i = 0,
split = null,
key = null,
value = null,
splitParts = null;
if (clearForm)
{
$('input[type="checkbox"],input[type="radio"]', element).removeAttr('checked');
$('select,input[type="text"],input[type="password"],input[type="hidden"],textarea', element).val('');
}
var kv = {};
while(split = splits[i++]){
splitParts = split.split('=');
key = splitParts[0] || '';
value = (splitParts[1] || '').replace(/\+/g, ' ');
if (key != ''){
if( key in kv ){
if( $.type(kv[key]) !== 'array' )
kv[key] = [kv[key]];
kv[key].push(value);
}else
kv[key] = value;
}
}
for( key in kv ){
value = kv[key];
$('input[type="checkbox"][name="'+ key +'"][value="'+ value +'"],input[type="radio"][name="'+ key +'"][value="'+ value +'"]', element).attr('checked', 'checked');
$('select[name="'+ key +'"],input[type="text"][name="'+ key +'"],input[type="password"][name="'+ key +'"],input[type="hidden"][name="'+ key +'"],textarea[name="'+ key +'"]', element).val(value);
}
}
})(jQuery);