-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.smartCombo.js
527 lines (519 loc) · 16.6 KB
/
jquery.smartCombo.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
* Convierte un combo multiple en botones clickeables
* author: [email protected]
*
* version 2.0.2 01/2017
*
* what's new:
* -----------------------------+
* 2.0.2 03/2017
* Actualización. Si el nodo <option></option> está vacío y no tiene value, no se muestra
* Se agrega "populateLabels" como metodo público
* 2.0.1 01/2014
* Se agregó el método destroy() y algunos fixes menores.
* 2.0 08/2013
* Nuevo template para el plugin, codebeauty, y algunos fixes
* 1.5
* 1.0.5
* más bugfix(no selecciona el primer elemento cuando hay un elemento con selected="selected" desde el HTML). Agregado los comentarios
* 1.0.4.2
* css fixed en theme/pela
* br remove en el armado html
* 1.0.4.1
* Para un selector que refiera a varios elementos, los tomaba como uno solo. Por ejemplo $("#select1,#select2")
* 1.0.4
* Revisado el rendimiendo.
* 1.0.3
* bug en chrome, no dejaba de-seleccionar una opcion, en un combo multiple y en un combo multiple con optgroup
* 1.0.2
* En un select simple, al seleccionar un elemento por primera vez, estando anteriormente seleccionado
* el elemento superior, no actualizaba el valor seleccionado en el select. M?todo: updateSelect
*
* TODO:
* -----------------------------+
* resolver el pie "seleccionar todos / ninguno" de los combos multiples y multiples con optgroups
*/
;(function($, window, document, undefined) {
//'use strict';
var pluginName = "smartCombo", defaults = {
_class : 'sc',
_text_labelSimple : 'Seleccione una opción',
_text_labelMultiple : 'Seleccione opciones',
_open : false,
_wrapperPosition : 'absolute',
_closeOnClick : true,
_openOnMouseEnter : true,
_closeOnMouseLeave : true,
reArmOnLoad : true,
setAllSelectedTofalse: false,
_initialState : 'close',
showSelectedLabels : true,
openMethod : 'display',//display, slide, fade
closeMethod : 'display' //display, slide, fade
};
function Plugin(element, options) {
this.element = element; //elemento en el dom y marco
this.$element = $(element); //jquery object
this.sourceNode = this.$element.get(0); //objeto DOM
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.initDone = false;
if(!this.$element.attr("id")) { //solo en elementos con ID
$.error('smartCombo needs ID attribute.');
}
if(this.$element.prop('tagName') != "SELECT") { //solo se puede inicializar un SELECT
$.error('smartCombo only be applied to a SELECT tag (' + this.$element.prop('tagName') + ')');
}
this.props = {
multiple : this.$element.prop("multiple"),
destID : 'sc_' + this.$element.attr("id"),
_ulClass : 'sc_ul',
_liClass : 'sc_li',
_labelClass : 'sc_label',
_footerDivClass : 'sc_footer',
_footerAbt : 'sc_footerBT',
_footerBTall : 'sc_footerBTall',
_footerBTnone : 'sc_footerBTnone',
_liClassOptGroup : 'sc_optGroup',
_liClassOptGroupLabel : 'sc_optGroupLabel',
_wrapperClass : 'sc_wrapper',
_optionSelectedClass : 'sc_optionSelectedClass',
_optgroupSelectedClass: 'sc_optgroupSelectedClass',
_enabledClass : 'sc_enabled',
_disabledClass : 'sc_disabled',
_openedClass : 'sc_opened',
_closedClass : 'sc_closed',
disabled : false
};
this.init();
this.setActions();
this.setEvents();
this._public.reArmFromSource();
if(this.settings.reArmOnLoad) {
this.populateLabels();
}
if(this.settings._initialState == 'open') {
this.openWrapper();
}
this.$element.data("plugin_" + pluginName + "_context", this);
}
Plugin.prototype = {
_public : {
_parent : {},
destroy : function() {
var context = context || this._parent;
context.sc.remove();
context.$element.toggle().removeData("plugin_smartCombo").removeData("plugin_smartCombo_context");
},
enable : function(context) {
context = context || this._parent;
context.props.disabled = false;
context.sc.removeClass(context.props._disabledClass);
context.sc.addClass(context.props._enabledClass);
},
disable : function(context) {
context = context || this._parent;
context.props.disabled = true;
context.sc.removeClass(context.props._enabledClass);
context.sc.addClass(context.props._disabledClass);
},
populateLabels : function(context) {
context = context || this._parent;
context.populateLabels();
},
openWrapper : function(context) {
context = context || this._parent;
context.openWrapper();
},
closeWrapper : function(context) {
context = context || this._parent;
context.closeWrapper();
},
reArmFromSource: function(context) {
//rearma el sc desde el select
context = context || this._parent;
var indexes = [], vi;
for(vi = 0; vi < context.sourceNode.options.length; vi++) {
if(context.sourceNode.options.item(vi).selected) {
indexes.push(String(vi));
}
}
//recorre todas las opciones dentro del sc y si corresponde, aplica el selected
context.sc_options.each(
function() {
if(jQuery.inArray($(this).attr("index"), indexes) != -1) {
$(this).addClass(context.props._optionSelectedClass);
} else {
$(this).removeClass(context.props._optionSelectedClass);
}
}
);
//Pone selected en los optgroups si todas las opciones, dentro de un optgroup están seleccionadas
context.sc_optgroups.each(
function() {
var optgroupJQO = $(this), ok = true;
//todos los <a> dentro de <li>._liClass dentro de optgroupJQO
$("." + context.props._liClass + " a", optgroupJQO).each(
function() {
if(!$(this).hasClass(context.props._optionSelectedClass)) {
ok = false;
}
}
);
if(ok) {
optgroupJQO.data("seleccionado", true)
.children("a")
.addClass(context.props._optgroupSelectedClass);
} else {
optgroupJQO.data("seleccionado", false)
.children("a")
.removeClass(context.props._optgroupSelectedClass);
}
}
);
//si no es multiple o si _closeOnClick = true, entonces cierra el wrapper
if(!context.props.multiple && context.settings._closeOnClick) {
context.settings._open = context.closeWrapper();
}
}
},
init : function() {
this._public._parent = this;
var context = this;
var html = '';
html += '<div id="' + this.props.destID + '" class="' + this.settings._class + '">';
html += '<div class="' + this.props._labelClass + '">';
html += '<a href="javascript:;" title="' +
(
(this.props.multiple) ? this.settings._text_labelMultiple : this.settings._text_labelSimple
) +
'">' +
(
(this.props.multiple) ? this.settings._text_labelMultiple : this.settings._text_labelSimple) +
'</a>';
html += '</div>';
html +=
'<div class="' +
this.props._wrapperClass +
' ' +
this.props._closedClass +
'" style="position:' +
this.settings._wrapperPosition +
'">';
html += '<ul class="' + this.props._ulClass + '">';
this.$element.children("optgroup,option").each(
function() {
html += context.getNode($(this));
}
);
html += '</ul>';
html += '</div>';
html += '</div>';
this.$element.css("display", "none").after(html);
this.sc = $("#" + this.props.destID);
this.sc_options = $("." + this.props._liClass + " a", this.sc);
this.sc_label = $("." + this.props._labelClass + " a", this.sc);
this.sc_optgroups = $("." + this.props._liClassOptGroup + " a", this.sc);
this.sc_optgroups_labels = $("." + this.props._liClassOptGroupLabel, this.sc);
this.wrapper = $("." + this.props._wrapperClass, this.sc);
this.hasOptgrups = $("optgroup", this.$element).length > 0;
this.optgroups = $("optgroup", this.$element);
this.options = $("option", this.$element);
},
getNode : function($element) {
var context = this;
//obtiene el nodo optgroup o option y devuelve el html correspondiente
var html = '', JSOnode = $element.get(0);
if(JSOnode.tagName == "OPTGROUP") {
html += '<li class="' + this.props._liClassOptGroup + '">';
if(this.props.multiple) {
html +=
'<a href="javascript:;" class="' +
this.props._liClassOptGroupLabel +
'" title="' +
$element.attr("label") +
'">' +
$element.attr("label") +
'</a>';
} else {
html +=
'<span class="' + this.props._liClassOptGroupLabel + '" >' + $element.attr("label") + '</span>';
}
html += '<ul>';
$element.children("option").each(
function() {
html += context.getNode($(this));
}
);
html += '</ul>';
html += '</li>';
} else {
if($element.val() == "" && $element.text() == "") {
return ''; //si el elemento tiene value="" y no tiene texto (<option></option>) devolvemos vacío
}
html += '<li class="' + this.props._liClass + '" val="' + $element.val() + '">';
html += '<a href="javascript:;" inheritedValue="' + $element.val() + '" index="' + JSOnode.index + '">';
html += '<span>';
html += $element.html();
html += '</span>';
html += '</a>';
html += '</li>';
}
return html;
},
setActions : function() {
var context = this;
this.sc_label.click(
function() {
if(context.settings._closeOnClick && !context.props.disabled) {
context.settings._open = (
(context.settings._open) ? context.closeWrapper() : context.openWrapper()
);
}
}
);
this.sc_options.click(
function() {
if(!context.props.disabled) {
context.clickOnOption($(this));
}
}
);
if(this.props.multiple) { //si es multiple y tiene optgroups, click en el optgroup selecciona (o no) todas las opciones
this.sc_optgroups_labels.click(
function() {
if(!context.props.disabled) {
context.clickOnOptGroup($(this).parent());
}
}
);
}
},
setEvents : function() {
var context = this;
if(this.settings._openOnMouseEnter) {
this.sc.bind(
'mouseenter', function() {
if(!context.props.disabled) {
context.settings._open = context.openWrapper();
}
}
);
}
if(this.settings._closeOnMouseLeave && this.settings._closeOnClick) {
this.sc.bind(
'mouseleave', function() {
if(!context.props.disabled) {
context.settings._open = context.closeWrapper();
}
}
);
}
},
populateLabels : function() {
//obtiene los labels de los options seleccionados y los pone en sc_label
var tmp = [];
$("." + this.props._optionSelectedClass + " span", this.sc).each(
function() {
tmp.push($(this).html());
}
);
this.sc.data("labels", tmp);
var label = tmp.join(", ");
if(label == '') {
this.sc_label.removeClass("selected");
label = (
(this.props.multiple) ? this.settings._text_labelMultiple : this.settings._text_labelSimple
);
} else {
this.sc_label.addClass("selected");
}
if(this.settings.showSelectedLabels) {
this.sc_label.html(label);
}
this.sc_label.attr("title", label);
},
clickOnOptGroup: function(optgroup) {
var context = this;
if(!context.props.disabled) {
//click en un optgroup
if(optgroup.data("seleccionado")) {
$("." + this.props._liClass + " a", optgroup).removeClass(this.props._optionSelectedClass);
optgroup.data("seleccionado", false).children("a").removeClass(this.props._optgroupSelectedClass);
} else {
$("." + this.props._liClass + " a", optgroup).addClass(this.props._optionSelectedClass);
optgroup.data("seleccionado", true).children("a").addClass(this.props._optgroupSelectedClass);
}
this.populateLabels();
this.updateSelect();
}
},
updateSelect : function() {
//rearma el select, desde el SC, despues de que se clickea una opcion en el sc
var context = this, indexes = [], c;
this.sc_options.each(
function() {
if($(this).hasClass(context.props._optionSelectedClass)) {
indexes.push($(this).attr("index"));
}
}
);
//selecciona las indicadas y de-selecciona las demás
for(c = 0; c < this.sourceNode.options.length; c++) {
this.sourceNode.options.item(c).selected = jQuery.inArray(String(c), indexes) != -1;
}
//rearma el sc
this._public.reArmFromSource();
context.populateLabels();
//dispara el evento change()
this.$element.change();
},
openWrapper : function() {
var context = this;
if(!this.props.disabled) {
switch(this.settings.openMethod) {
case 'fade':
this.wrapper
.css(
{
"opacity": 0,
"display": "block"
}
)
.stop(true, true)
.fadeIn(
function() {
$(this)
.addClass(context.props._openedClass)
.removeClass(context.props._closedClass);
}
);
break;
case 'slide':
this.wrapper
.stop(true, true)
.slideDown(
function() {
$(this)
.addClass(context.props._openedClass)
.removeClass(context.props._closedClass);
}
);
break;
default:
case 'display':
this.wrapper
.css("display", "block")
.addClass(context.props._openedClass)
.removeClass(context.props._closedClass);
break;
}
return true;
} else {
return this.settings._open;
}
},
closeWrapper : function() {
var context = this;
if(!this.props.disabled) {
switch(this.settings.closeMethod) {
case 'fade':
this.wrapper
.stop(true, true)
.fadeOut(
function() {
$(this)
.css("display", "none")
.addClass(context.props._closedClass)
.removeClass(context.props._openedClass);
}
);
break;
case 'slide':
this.wrapper
.stop(true, true)
.slideUp(
function() {
$(this)
.addClass(context.props._closedClass)
.removeClass(context.props._openedClass);
}
);
break;
default:
case 'display':
this.wrapper
.css("display", "none")
.addClass(context.props._closedClass)
.removeClass(context.props._openedClass);
break;
}
return false;
} else {
return this.settings._open;
}
},
clickOnOption : function(selectedOption) {
var context = this;
if(!context.props.disabled) {
//click en una opcion
if(!this.props.multiple) { //si no es múltiple, entonces remueve el selected de todas las opciones
this.sc_options.removeClass(this.props._optionSelectedClass);
if(this.settings._closeOnClick) { //si _closeOnClick = true, cierra wrapper
this.settings._open = this.closeWrapper();
}
}
if(selectedOption.hasClass(this.props._optionSelectedClass)) {
selectedOption.removeClass(this.props._optionSelectedClass);
} else {
selectedOption.addClass(this.props._optionSelectedClass);
}
var optgroupJQO = selectedOption.parent().parent().parent();
if(optgroupJQO.length > 0) {
var ok = true;
$("." + this.props._liClass + " a", optgroupJQO).each(
function() {
if(!$(this).hasClass(context.props._optionSelectedClass)) {
ok = false;
}
}
);
if(ok) {
optgroupJQO
.data("seleccionado", true)
.children("a")
.addClass(this.props._optgroupSelectedClass);
} else {
optgroupJQO
.data("seleccionado", false)
.children("a")
.removeClass(this.props._optgroupSelectedClass);
}
}
this.populateLabels();
this.updateSelect();
}
}
};
$.fn[pluginName] = function(method, opts) {
return this.each(
function() {
//si no está instanciado
if(!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, method));
} else {
//llamamos un metodo?
if(typeof $(this).data("plugin_" + pluginName)._public[method] === 'function') {
$(this).data("plugin_" + pluginName)._public[method](
$(this)
.data("plugin_" + pluginName + "_context"), opts
);
} else {
$.error('Method ' + method + ' does not exist on jQuery.smartCombo');
}
}
}
);
};
})(jQuery, window, document);