PageSourceSearch

https://www.water.gov.my/assets/shared/scripts/multiselect/js/jquery.select-multiple.js

js water.gov.my collected 2026-10-01 11:25:15 UTC 15,506 bytes, 456 lines download raw bytes

1/*
2* SelectMultiple v0.1
3* Copyright (c) 2015 krazedkrish( Shalil Awaley )
4*
5* This program is free software. It comes without any warranty, to
6* the extent permitted by applicable law. You can redistribute it
7* and/or modify it under the terms of the MIT LICENSE.
8* See https://en.wikipedia.org/wiki/MIT_License for more details.
9*/
10
11!function ($) {
12
13  "use strict";
14
15
16 /* SELECTMULTIPLE CLASS DEFINITION
17  * ====================== */
18
19  var SelectMultiple = function (element, options) {
20    this.options = options;
21    this.$element = $(element);
22    this.$container = $('<div/>', { 'class': "ms-container" });
23    this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' });
24    this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
25    this.scrollTo = 0;
26    this.elemsSelector = 'li';
27  };
28
29  SelectMultiple.prototype = {
30    constructor: SelectMultiple,
31
32    init: function(){
33      var that = this,
34          ms = this.$element;
35
36      if (ms.next('.ms-container').length === 0){
37        ms.css({ position: 'absolute', left: '-9999px' });
38        ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'selectmultiple');
39        this.$container.attr('id', 'ms-'+ms.attr('id'));
40        this.$container.addClass(that.options.cssClass);
41        ms.find('option').each(function(){
42          that.generateLisFromOption(this);
43        });
44
45
46        if (that.options.selectableHeader){
47          that.$selectableContainer.append(that.options.selectableHeader);
48        }
49        that.$selectableContainer.append(that.$selectableUl);
50        if (that.options.selectableFooter){
51          that.$selectableContainer.append(that.options.selectableFooter);
52        }
53
54
55        that.$container.append(that.$selectableContainer);
56        ms.after(that.$container);
57
58        that.activeMouse(that.$selectableUl);
59        that.activeKeyboard(that.$selectableUl);
60
61        var action = that.options.dblClick ? 'dblclick' : 'click';
62
63        that.$selectableUl.on(action, '.ms-elem-selectable', function(){
64          that.select($(this).data('ms-value'));
65        });
66
67
68        ms.on('focus', function(){
69          that.$selectableUl.focus();
70        })
71      }
72
73      var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get();
74      that.select(selectedValues, 'init');
75
76      if (typeof that.options.afterInit === 'function') {
77        that.options.afterInit.call(this, this.$container);
78      }
79    },
80
81    'generateLisFromOption' : function(option, index, $container){
82      var that = this,
83          ms = that.$element,
84          attributes = "",
85          $option = $(option);
86
87      for (var cpt = 0; cpt < option.attributes.length; cpt++){
88        var attr = option.attributes[cpt];
89
90        if(attr.name !== 'value' && attr.name !== 'disabled'){
91          attributes += attr.name+'="'+attr.value+'" ';
92        }
93      }
94      var selectableLi = $('<li '+attributes+'><span>'+that.escapeHTML($option.text())+'</span><span class="pull-right ms-elem-selected">✔</span></li>'),
95          selectedLi = selectableLi.clone(),
96          value = $option.val(),
97          elementId = that.sanitize(value);
98
99      selectableLi.children('.ms-elem-selected').hide();
100
101      selectableLi
102        .data('ms-value', value)
103        .addClass('ms-elem-selectable')
104        .attr('id', elementId+'-selectable');
105
106
107      if ($option.prop('disabled') || ms.prop('disabled')){
108        selectableLi.addClass(that.options.disabledClass);
109      }
110
111      var $optgroup = $option.parent('optgroup');
112
113      if ($optgroup.length > 0){
114        var optgroupLabel = $optgroup.attr('label'),
115            optgroupId = that.sanitize(optgroupLabel),
116            $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId);
117
118        if ($selectableOptgroup.length === 0){
119          var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>',
120              optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>';
121
122          $selectableOptgroup = $(optgroupContainerTpl);
123          $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId);
124          $selectableOptgroup.append($(optgroupTpl));
125          if (that.options.selectableOptgroup){
126            $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){
127              var values = $optgroup.children(':not(:selected, :disabled)').map(function(){ return $(this).val() }).get();
128              that.select(values);
129            });
130          }
131          that.$selectableUl.append($selectableOptgroup);
132        }
133        index = index == undefined ? $selectableOptgroup.find('ul').children().length : index + 1;
134        selectableLi.insertAt(index, $selectableOptgroup.children());
135      } else {
136        index = index == undefined ? that.$selectableUl.children().length : index;
137
138        selectableLi.insertAt(index, that.$selectableUl);
139      }
140    },
141
142    'addOption' : function(options){
143      var that = this;
144
145      if (options.value !== undefined && options.value !== null){
146        options = [options];
147      }
148      $.each(options, function(index, option){
149        if (option.value !== undefined && option.value !== null &&
150            that.$element.find("option[value='"+option.value+"']").length === 0){
151          var $option = $('<option value="'+option.value+'">'+option.text+'</option>'),
152              index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),
153              $container = option.nested == undefined ? that.$element : $("optgroup[label='"+option.nested+"']")
154
155          $option.insertAt(index, $container);
156          that.generateLisFromOption($option.get(0), index, option.nested);
157        }
158      })
159    },
160
161    'escapeHTML' : function(text){
162      return $("<div>").text(text).html();
163    },
164
165    'activeKeyboard' : function($list){
166      var that = this;
167
168      $list.on('focus', function(){
169        $(this).addClass('ms-focus');
170      })
171      .on('blur', function(){
172        $(this).removeClass('ms-focus');
173      })
174      .on('keydown', function(e){
175        switch (e.which) {
176          case 40:
177          case 38:
178            e.preventDefault();
179            e.stopPropagation();
180            that.moveHighlight($(this), (e.which === 38) ? -1 : 1);
181            return;
182          case 9:
183            if(that.$element.is('[tabindex]')){
184              e.preventDefault();
185              var tabindex = parseInt(that.$element.attr('tabindex'), 10);
186              tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1;
187              $('[tabindex="'+(tabindex)+'"]').focus();
188              return;
189            }else{
190              if(e.shiftKey){
191                that.$element.trigger('focus');
192              }
193            }
194        }
195        if($.inArray(e.which, that.options.keySelect) > -1){
196          e.preventDefault();
197          e.stopPropagation();
198          that.selectHighlighted($list);
199          return;
200        }
201      });
202    },
203
204    'moveHighlight': function($list, direction){
205      var $elems = $list.find(this.elemsSelector),
206          $currElem = $elems.filter('.ms-hover'),
207          $nextElem = null,
208          elemHeight = $elems.first().outerHeight(),
209          containerHeight = $list.height(),
210          containerSelector = '#'+this.$container.prop('id');
211
212      $elems.removeClass('ms-hover');
213      if (direction === 1){ // DOWN
214
215        $nextElem = $currElem.nextAll(this.elemsSelector).first();
216        if ($nextElem.length === 0){
217          var $optgroupUl = $currElem.parent();
218
219          if ($optgroupUl.hasClass('ms-optgroup')){
220            var $optgroupLi = $optgroupUl.parent(),
221                $nextOptgroupLi = $optgroupLi.next(':visible');
222
223            if ($nextOptgroupLi.length > 0){
224              $nextElem = $nextOptgroupLi.find(this.elemsSelector).first();
225            } else {
226              $nextElem = $elems.first();
227            }
228          } else {
229            $nextElem = $elems.first();
230          }
231        }
232      } else if (direction === -1){ // UP
233
234        $nextElem = $currElem.prevAll(this.elemsSelector).first();
235        if ($nextElem.length === 0){
236          var $optgroupUl = $currElem.parent();
237
238          if ($optgroupUl.hasClass('ms-optgroup')){
239            var $optgroupLi = $optgroupUl.parent(),
240                $prevOptgroupLi = $optgroupLi.prev(':visible');
241
242            if ($prevOptgroupLi.length > 0){
243              $nextElem = $prevOptgroupLi.find(this.elemsSelector).last();
244            } else {
245              $nextElem = $elems.last();
246            }
247          } else {
248            $nextElem = $elems.last();
249          }
250        }
251      }
252      if ($nextElem.length > 0){
253        $nextElem.addClass('ms-hover');
254        var scrollTo = $list.scrollTop() + $nextElem.position().top -
255                       containerHeight / 2 + elemHeight / 2;
256
257        $list.scrollTop(scrollTo);
258      }
259    },
260
261    'selectHighlighted' : function($list){
262      var $elems = $list.find(this.elemsSelector),
263          $highlightedElem = $elems.filter('.ms-hover').first();
264
265      if ($highlightedElem.length > 0){
266        if ($list.parent().hasClass('ms-selectable')){
267          this.select($highlightedElem.data('ms-value'));
268        } else {
269          this.deselect($highlightedElem.data('ms-value'));
270        }
271        $elems.removeClass('ms-hover');
272      }
273    },
274
275    'activeMouse' : function($list){
276      var that = this;
277
278      $('body').on('mouseenter', that.elemsSelector, function(){
279        $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
280        $(this).addClass('ms-hover');
281      });
282
283      $('body').on('mouseleave', that.elemsSelector, function () {
284          $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');;
285      });
286    },
287
288    'refresh' : function() {
289      this.destroy();
290      this.$element.selectMultiple(this.options);
291    },
292
293    'destroy' : function(){
294      $("#ms-"+this.$element.attr("id")).remove();
295      this.$element.css('position', '').css('left', '')
296      this.$element.removeData('selectmultiple');
297    },
298
299    'select' : function(value, method){
300      if (typeof value === 'string'){ value = [value]; }
301
302      var that = this,
303          ms = this.$element,
304          msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
305          selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
306          options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
307
308      if (method === 'init'){
309        selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable');
310      }
311
312      if (selectables.length > 0){
313        selectables.addClass('ms-selected').children('.ms-elem-selected').show();
314
315        if (method !== 'init' && options.prop('selected') == true) {
316          that.deselect(value, method);
317          return;
318        }
319
320        options.prop('selected', true);
321
322        var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
323        if (selectableOptgroups.length > 0){
324          selectableOptgroups.each(function(){
325            var selectablesLi = $(this).find('.ms-elem-selectable');
326            if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
327              $(this).find('.ms-optgroup-label').hide();
328            }
329          });
330
331        }
332        if (method !== 'init'){
333          ms.trigger('change');
334          if (typeof that.options.afterSelect === 'function') {
335            that.options.afterSelect.call(this, value);
336          }
337        }
338      }
339    },
340
341    'deselect' : function(value, method){
342      if (typeof value === 'string'){ value = [value]; }
343
344      var that = this,
345          ms = this.$element,
346          msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
347          selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
348          options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
349
350      selectables.removeClass('ms-selected').children('.ms-elem-selected').hide();
351      options.prop('selected', false);
352
353      var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
354      if (selectableOptgroups.length > 0){
355        selectableOptgroups.each(function(){
356          var selectablesLi = $(this).find('.ms-elem-selectable');
357          if (selectablesLi.filter(':not(.ms-selected)').length > 0){
358            $(this).find('.ms-optgroup-label').show();
359          }
360        });
361
362      }
363      if (method !== 'init'){
364        ms.trigger('change');
365        if (typeof that.options.afterDeselect === 'function') {
366          that.options.afterDeselect.call(this, value);
367        }
368      }
369    },
370
371    'select_all' : function(){
372      var ms = this.$element,
373          values = ms.val();
374
375      ms.find('option:not(":disabled")').prop('selected', true);
376      this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').children('.ms-elem-selected').show();
377      this.$selectableUl.find('.ms-optgroup-label').hide();
378      ms.trigger('change');
379      if (typeof this.options.afterSelect === 'function') {
380        var selectedValues = $.grep(ms.val(), function(item){
381          return $.inArray(item, values) < 0;
382        });
383        this.options.afterSelect.call(this, selectedValues);
384      }
385    },
386
387    'deselect_all' : function(){
388      var ms = this.$element,
389          values = ms.val();
390
391      ms.find('option').prop('selected', false);
392      this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').children('.ms-elem-selected').hide();
393      this.$selectableUl.find('.ms-optgroup-label').show();
394      this.$selectableUl.focus();
395      ms.trigger('change');
396      if (typeof this.options.afterDeselect === 'function') {
397        this.options.afterDeselect.call(this, values);
398      }
399    },
400
401    sanitize: function(value){
402      var hash = 0, i, character;
403      if (value.length == 0) return hash;
404      var ls = 0;
405      for (i = 0, ls = value.length; i < ls; i++) {
406        character  = value.charCodeAt(i);
407        hash  = ((hash<<5)-hash)+character;
408        hash |= 0; // Convert to 32bit integer
409      }
410      return hash;
411    }
412  };
413
414  /* SELECTMULTIPLE PLUGIN DEFINITION
415   * ======================= */
416
417  $.fn.selectMultiple = function () {
418    var option = arguments[0],
419        args = arguments;
420
421    return this.each(function () {
422      var $this = $(this),
423          data = $this.data('selectmultiple'),
424          options = $.extend({}, $.fn.selectMultiple.defaults, $this.data(), typeof option === 'object' && option);
425
426      if (!data){ $this.data('selectmultiple', (data = new SelectMultiple(this, options))); }
427
428      if (typeof option === 'string'){
429        data[option](args[1]);
430      } else {
431        data.init();
432      }
433    });
434  };
435
436  $.fn.selectMultiple.defaults = {
437    keySelect: [32],
438    selectableOptgroup: false,
439    disabledClass : 'disabled',
440    dblClick : false,
441    cssClass: ''
442  };
443
444  $.fn.selectMultiple.Constructor = SelectMultiple;
445
446  $.fn.insertAt = function(index, $parent) {
447    return this.each(function() {
448      if (index === 0) {
449        $parent.prepend(this);
450      } else {
451        $parent.children().eq(index - 1).after(this);
452      }
453    });
454}
455
456}(window.jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.