forked from airhorns/jQuery-Chained-Select
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.chainedselect.js
230 lines (214 loc) · 8.17 KB
/
jquery.chainedselect.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/**
* jQuery ChainedSelect
*
* Chain multiple select lists to each other, so changing an option in one
* (the parent) modifies the options in the others (the targets).
*
* Based on Remy Sharp's "selectChain" plugin, available at:
* http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/
*
* @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
* @requires jQuery 1.2.6 or later
*
* Licensed under the New BSD License
* See: http://www.opensource.org/licenses/bsd-license.php
*/
(function($) {
$.fn.chainedSelect = function(options) {
var settings = $.extend({}, $.fn.chainedSelect.defaults, options);
var cache;
if(settings.globalCache) {
if(typeof $.fn.chainedSelect._globalCache == "undefined") {
$.fn.chainedSelect._globalCache = settings.cacheClass(settings);
}
cache = $.fn.chainedSelect._globalCache;
} else {
cache = settings.cacheClass(settings);
}
return this.each(function() {
var $$ = $(this);
// Load metadata for this Select element, if available:
var opts = $.metadata ? $.extend({}, settings, $$.metadata()) : settings;
// Add a preloader GIF beside this element, if "preloadUrl" is present:
var showPreloader, hidePreloader;
if (opts.preloadUrl) {
opts.preloader = $('<img />').css({
position: 'absolute',
border: 'none',
display: 'none'
}).attr('src', opts.preloadUrl);
$$.after(opts.preloader);
showPreloader = function() {
opts.preloader.css({
left: $$.position().left + $$.outerWidth() + 5,
top: $$.position().top + ($$.outerHeight()/2) - 8
}).show();
};
hidePreloader = function() {
opts.preloader.hide();
};
} else {
showPreloader = hidePreloader = function(){};
}
if (!(opts.parent instanceof $)) opts.parent = $(opts.parent);
opts.parent.change(function() {
var param = $(this).val();
$$.attr('disabled', 'disabled');
var key = getCacheKey($$, opts, param);
var data = cache.getItem(key);
if (data) {
addOptions($$, opts, data);
$$.effect("highlight", {}, 1000);
} else {
showPreloader();
$.ajax({
url: opts.url,
data: {'q': param},
type: (opts.type || 'get'),
dataType: 'json',
global: false,
success: function(data) {
addOptions($$, opts, data);
hidePreloader();
cache.setItem(key, data);
},
error: function(xhr, msg, e) {
if (opts.error) opts.error(xhr, msg, e);
}
});
}
});
var parent_val = opts.parent.val();
if (parent_val) {
if(opts.initialLoad) {
// If the parent list has a selected value, trigger
// its "change" event so chained lists can update
// their options:
opts.parent.trigger('change');
} else {
// This select is already popuplated with assumed appropriate options.
// Load them into the cache.
var row = {};
cache.setItem(getCacheKey($$, opts, parent_val), $$.children('option').map(function(i,e) {
row = {};
row[opts.value] = $(e).val();
row[opts.label] = $(e).text();
$.each($(e.attributes), function(j) {
if(e.attributes[j].name.indexOf('data-') == 0) {
row[e.attributes[j].name.substr(5)] = e.attributes[j].value;
}
});
return row;
}).get()
);
}
}
});
};
function getCacheKey(target, opts, param) {
var key;
if(opts.cacheKey) {
key = opts.cacheKey + '::' + param;
} else {
key = target.attr('id') + '::' + param;
}
return key;
};
function addOptions(target, opts, data) {
var curValue = target.val();
target.empty();
for (i=0; i<data.length; i++) {
var value, label, opt, temp;
if (typeof data[i] == 'object') {
value = data[i][opts.value];
label = data[i][opts.label];
} else {
value = label = data[i];
}
// Add new option to the DOM
target.get(0).options[i] = new Option(label, value);
// Add any extra datas present in the data as data attributes on the option
if (typeof data[i] == 'object') {
opt = $(target.get(0).options[i]);
for(name in data[i]) {
if(name != opts.value && name != opts.label) {
opt.attr('data-'+name, data[i][name]);
}
}
}
}
// Restore the previous selection. If nothing was selected
// before, select the first option:
if (curValue && $.inArray(curValue,
target.find('option').map(function(){
return $(this).val();
}).get() ) != -1
) {
target.val(curValue);
} else {
target.find('option:first').attr('selected', 'selected');
}
// Trigger the change event, so other lists chained to this
// one get updated too:
target.attr('disabled', '').trigger('change');
// Trigger success callback
opts.success(data);
}
/*
* A Quick-n-dirty LRU cache.
*
* This probably isn't the best implementation, but it works fine
* for me...KISS, and all that :)
*
* If you'd like something more fancy, check out: http://monsur.com/projects/jscache/
* You can supply a different cache class by either overriding the default, or
* passing it as an option, in the call to "chainedSelect".
*
* Your custom cache class must implement the following methods:
*
* getItem(key): Get the item with the specified "key" from the cache.
*
* setItem(key, value): Add "value" to the cache under the supplied "key".
*
* clear(): Clear all items from the cache (not currently used).
*
* In addition, its constructor should take a single argument; it'll be passed a hash
* of options used to initialize the plugin.
*/
$.fn.chainedSelect.Cache = function(opts) {
var cache = {},
keys = [];
return {
getItem: function(key) {
if (key in cache) return cache[key];
else return null;
},
setItem: function(key, value) {
if (value) {
cache[key] = value;
var length = keys.push(key);
if (length > opts.cacheLength) {
delete cache[keys.shift()];
}
}
},
clear: function() {
cache = {};
keys = [];
}
};
};
/* Plugin defaults */
$.fn.chainedSelect.defaults = {
value: 'pk', // The name of the field containing the option's value
label: 'name', // The name of the field containing text for the option's label
preloadUrl: '', // The URL to a GIF image to be used as a preloader
globalCache: false, // Weather or not to use a global cache for all chained selects on the page
cacheClass: $.fn.chainedSelect.Cache, // The cache used to store the results of AJAX calls
cacheLength: 100, // The maximum number of entries that should be cached
cacheKey: false, // The custom overridden cache key to use for these selects
error: null, // Function called if an AJAX call returns an error
initialLoad: true, // Weather or not to fetch the list if the parent already has a value
success: jQuery.noop
};
})(jQuery);