Best Python code snippet using autotest_python
jquery.selectBox.js
Source:jquery.selectBox.js  
1/*2 * jQuery selectBox - A cosmetic, styleable replacement for SELECT elements3 *4 * Licensed under the MIT license: http://opensource.org/licenses/MIT5 *6 * v1.2.07 *8 * https://github.com/marcj/jquery-selectBox9 */10;(function ($) {11    /**12     * SelectBox class.13     *14     * @param {HTMLElement|jQuery} select If it's a jQuery object, we use the first element.15     * @param {Object}             options16     * @constructor17     */18    var SelectBox = this.SelectBox = function (select, options) {19        if (select instanceof jQuery) {20            if (select.length > 0) {21                select = select[0];22            } else {23                return;24            }25        }26        this.typeTimer     = null;27        this.typeSearch    = '';28        this.isMac         = navigator.platform.match(/mac/i);29        options            = 'object' === typeof options ? options :  {};30        this.selectElement = select;31        // Disable for iOS devices (their native controls are more suitable for a touch device)32        if (!options.mobile && navigator.userAgent.match(/iPad|iPhone|Android|IEMobile|BlackBerry/i)) {33            return false;34        }35        // Element must be a select control36        if ('select' !== select.tagName.toLowerCase()) {37            return false;38        }39        this.init(options);40    }41    /**42     * @type {String}43     */44    SelectBox.prototype.version = '1.2.0';45    /**46     * @param {Object} options47     *48     * @returns {Boolean}49     */50    SelectBox.prototype.init = function (options) {51        var select = $(this.selectElement);52        if (select.data('selectBox-control')) {53            return false;54        }55        var control    = $('<a class="selectBox" />')56            , inline   = select.attr('multiple') || parseInt(select.attr('size')) > 157            , settings = options || {}58            , tabIndex = parseInt(select.prop('tabindex')) || 059            , self     = this;60        control61            .width(select.outerWidth())62            .addClass(select.attr('class'))63            .attr('title', select.attr('title') || '')64            .attr('tabindex', tabIndex)65            .css('display', 'inline-block')66            .bind('focus.selectBox', function () {67                if (this !== document.activeElement && document.body !== document.activeElement) {68                    $(document.activeElement).blur();69                }70                if (control.hasClass('selectBox-active')) {71                    return;72                }73                control.addClass('selectBox-active');74                select.trigger('focus');75            })76            .bind('blur.selectBox', function () {77                if (!control.hasClass('selectBox-active')) {78                    return;79                }80                control.removeClass('selectBox-active');81                select.trigger('blur');82            });83        if (!$(window).data('selectBox-bindings')) {84            $(window)85                .data('selectBox-bindings', true)86                .bind('scroll.selectBox', this.hideMenus)87                .bind('resize.selectBox', this.hideMenus);88        }89        if (select.attr('disabled')) {90            control.addClass('selectBox-disabled');91        }92        // Focus on control when label is clicked93        select.bind('click.selectBox', function (event) {94            control.focus();95            event.preventDefault();96        });97        // Generate control98        if (inline) {99            // Inline controls100            options = this.getOptions('inline');101            control102                .append(options)103                .data('selectBox-options', options).addClass('selectBox-inline selectBox-menuShowing')104                .bind('keydown.selectBox', function (event) {105                    self.handleKeyDown(event);106                })107                .bind('keypress.selectBox',function (event) {108                    self.handleKeyPress(event);109                })110                .bind('mousedown.selectBox',function (event) {111                    if (1 !== event.which) {112                        return;113                    }114                    if ($(event.target).is('A.selectBox-inline')) {115                        event.preventDefault();116                    }117                    if (!control.hasClass('selectBox-focus')) {118                        control.focus();119                    }120                })121                .insertAfter(select);122            // Auto-height based on size attribute123            if (!select[0].style.height) {124                var size = select.attr('size') ? parseInt(select.attr('size')) : 5;125                // Draw a dummy control off-screen, measure, and remove it126                var tmp = control127                    .clone()128                    .removeAttr('id')129                    .css({130                        position: 'absolute',131                        top: '-9999em'132                    })133                    .show()134                    .appendTo('body');135                tmp.find('.selectBox-options').html('<li><a>\u00A0</a></li>');136                var optionHeight = parseInt(tmp.find('.selectBox-options A:first').html(' ').outerHeight());137                tmp.remove();138                control.height(optionHeight * size);139            }140            this.disableSelection(control);141        } else {142            // Dropdown controls143            var label = $('<span class="selectBox-label" />'),144                arrow = $('<span class="selectBox-arrow" />');145            // Update label146            label.attr('class', this.getLabelClass()).text(this.getLabelText());147            options = this.getOptions('dropdown');148            options.appendTo('BODY');149            control150                .data('selectBox-options', options)151                .addClass('selectBox-dropdown')152                .append(label)153                .append(arrow)154                .bind('mousedown.selectBox', function (event) {155                    if (1 === event.which) {156                        if (control.hasClass('selectBox-menuShowing')) {157                            self.hideMenus();158                        } else {159                            event.stopPropagation();160                            // Webkit fix to prevent premature selection of options161                            options162                                .data('selectBox-down-at-x', event.screenX)163                                .data('selectBox-down-at-y', event.screenY);164                            self.showMenu();165                        }166                    }167                })168                .bind('keydown.selectBox', function (event) {169                    self.handleKeyDown(event);170                })171                .bind('keypress.selectBox', function (event) {172                    self.handleKeyPress(event);173                })174                .bind('open.selectBox',function (event, triggerData) {175                    if (triggerData && triggerData._selectBox === true) {176                        return;177                    }178                    self.showMenu();179                })180                .bind('close.selectBox', function (event, triggerData) {181                    if (triggerData && triggerData._selectBox === true) {182                        return;183                    }184                    self.hideMenus();185                })186                .insertAfter(select);187            // Set label width188            var labelWidth =189                    control.width()190                  - arrow.outerWidth()191                  - parseInt(label.css('paddingLeft')) || 0192                  - parseInt(label.css('paddingRight')) || 0;193            label.width(labelWidth);194            this.disableSelection(control);195        }196        // Store data for later use and show the control197        select198            .addClass('selectBox')199            .data('selectBox-control', control)200            .data('selectBox-settings', settings)201            .hide();202    };203    /**204     * @param {String} type 'inline'|'dropdown'205     * @returns {jQuery}206     */207    SelectBox.prototype.getOptions = function (type) {208        var options;209        var select = $(this.selectElement);210        var self   = this;211        // Private function to handle recursion in the getOptions function.212        var _getOptions = function (select, options) {213            // Loop through the set in order of element children.214            select.children('OPTION, OPTGROUP').each(function () {215                // If the element is an option, add it to the list.216                if ($(this).is('OPTION')) {217                    // Check for a value in the option found.218                    if ($(this).length > 0) {219                        // Create an option form the found element.220                        self.generateOptions($(this), options);221                    } else {222                        // No option information found, so add an empty.223                        options.append('<li>\u00A0</li>');224                    }225                } else {226                    // If the element is an option group, add the group and call this function on it.227                    var optgroup = $('<li class="selectBox-optgroup" />');228                    optgroup.text($(this).attr('label'));229                    options.append(optgroup);230                    options = _getOptions($(this), options);231                }232            });233            // Return the built strin234            return options;235        };236        switch (type) {237            case 'inline':238                options = $('<ul class="selectBox-options" />');239                options = _getOptions(select, options);240                options241                    .find('A')242                    .bind('mouseover.selectBox', function (event) {243                        self.addHover($(this).parent());244                    })245                    .bind('mouseout.selectBox',function (event) {246                        self.removeHover($(this).parent());247                    })248                    .bind('mousedown.selectBox',function (event) {249                        if (1 !== event.which) {250                            return251                        }252                        event.preventDefault(); // Prevent options from being "dragged"253                        if (!select.selectBox('control').hasClass('selectBox-active')) {254                            select.selectBox('control').focus();255                        }256                    })257                    .bind('mouseup.selectBox', function (event) {258                        if (1 !== event.which) {259                            return;260                        }261                        self.hideMenus();262                        self.selectOption($(this).parent(), event);263                    });264                this.disableSelection(options);265                return options;266            case 'dropdown':267                options = $('<ul class="selectBox-dropdown-menu selectBox-options" />');268                options = _getOptions(select, options);269                options270                    .data('selectBox-select', select)271                    .css('display', 'none')272                    .appendTo('BODY')273                    .find('A')274                    .bind('mousedown.selectBox', function (event) {275                        if (event.which === 1) {276                            event.preventDefault(); // Prevent options from being "dragged"277                            if (event.screenX === options.data('selectBox-down-at-x') &&278                                event.screenY === options.data('selectBox-down-at-y')) {279                                options.removeData('selectBox-down-at-x').removeData('selectBox-down-at-y');280                                self.hideMenus();281                            }282                        }283                    })284                    .bind('mouseup.selectBox', function (event) {285                        if (1 !== event.which) {286                            return;287                        }288                        if (event.screenX === options.data('selectBox-down-at-x') &&289                            event.screenY === options.data('selectBox-down-at-y')) {290                            return;291                        } else {292                            options.removeData('selectBox-down-at-x').removeData('selectBox-down-at-y');293                        }294                        self.selectOption($(this).parent());295                        self.hideMenus();296                    })297                    .bind('mouseover.selectBox', function (event) {298                        self.addHover($(this).parent());299                    })300                    .bind('mouseout.selectBox', function (event) {301                        self.removeHover($(this).parent());302                    });303                // Inherit classes for dropdown menu304                var classes = select.attr('class') || '';305                if ('' !== classes) {306                    classes = classes.split(' ');307                    for (var i in classes) {308                        options.addClass(classes[i] + '-selectBox-dropdown-menu');309                    }310                }311                this.disableSelection(options);312                return options;313        }314    };315    /**316     * Returns the current class of the selected option.317     *318     * @returns {String}319     */320    SelectBox.prototype.getLabelClass = function () {321        var selected = $(this.selectElement).find('OPTION:selected');322        return ('selectBox-label ' + (selected.attr('class') || '')).replace(/\s+$/, '');323    };324    /**325     * Returns the current label of the selected option.326     *327     * @returns {String}328     */329    SelectBox.prototype.getLabelText = function () {330        var selected = $(this.selectElement).find('OPTION:selected');331        return selected.text() || '\u00A0';332    };333    /**334     * Sets the label.335     * This method uses the getLabelClass() and getLabelText() methods.336     */337    SelectBox.prototype.setLabel = function () {338        var select = $(this.selectElement);339        var control = select.data('selectBox-control');340        if (!control) {341            return;342        }343        control344            .find('.selectBox-label')345            .attr('class', this.getLabelClass())346            .text(this.getLabelText());347    };348    /**349     * Destroys the SelectBox instance and shows the origin select element.350     *351     */352    SelectBox.prototype.destroy = function () {353        var select = $(this.selectElement);354        var control = select.data('selectBox-control');355        if (!control) {356            return;357        }358        var options = control.data('selectBox-options');359        options.remove();360        control.remove();361        select362            .removeClass('selectBox')363            .removeData('selectBox-control')364            .data('selectBox-control', null)365            .removeData('selectBox-settings')366            .data('selectBox-settings', null)367            .show();368    };369    /**370     * Refreshes the option elements.371     */372    SelectBox.prototype.refresh = function () {373        var select = $(this.selectElement),374            control = select.data('selectBox-control'),375            dropdown = control.hasClass('selectBox-dropdown'),376            menuOpened = control.hasClass('selectBox-menuShowing');377        select.selectBox('options', select.html());378        // Restore opened dropdown state (original menu was trashed)379        if (dropdown && menuOpened) {380            this.showMenu();381        }382    };383    /**384     * Shows the dropdown menu.385     */386    SelectBox.prototype.showMenu = function () {387        var self = this388            , select   = $(this.selectElement)389            , control  = select.data('selectBox-control')390            , settings = select.data('selectBox-settings')391            , options  = control.data('selectBox-options');392        if (control.hasClass('selectBox-disabled')) {393            return false;394        }395        this.hideMenus();396        var borderBottomWidth = parseInt(control.css('borderBottomWidth')) || 0;397        // Menu position398        options399            .width(control.innerWidth())400            .css({401                top: control.offset().top + control.outerHeight() - borderBottomWidth,402                left: control.offset().left403            });404        if (select.triggerHandler('beforeopen')) {405            return false;406        }407        var dispatchOpenEvent = function () {408            select.triggerHandler('open', {409                _selectBox: true410            });411        };412        // Show menu413        switch (settings.menuTransition) {414            case 'fade':415                options.fadeIn(settings.menuSpeed, dispatchOpenEvent);416                break;417            case 'slide':418                options.slideDown(settings.menuSpeed, dispatchOpenEvent);419                break;420            default:421                options.show(settings.menuSpeed, dispatchOpenEvent);422                break;423        }424        if (!settings.menuSpeed) {425            dispatchOpenEvent();426        }427        // Center on selected option428        var li = options.find('.selectBox-selected:first');429        this.keepOptionInView(li, true);430        this.addHover(li);431        control.addClass('selectBox-menuShowing');432        $(document).bind('mousedown.selectBox', function (event) {433            if (1 === event.which) {434                if ($(event.target).parents().andSelf().hasClass('selectBox-options')) {435                    return;436                }437                self.hideMenus();438            }439        });440    };441    /**442     * Hides the menu of all instances.443     */444    SelectBox.prototype.hideMenus = function () {445        if ($(".selectBox-dropdown-menu:visible").length === 0) {446            return;447        }448        $(document).unbind('mousedown.selectBox');449        $(".selectBox-dropdown-menu").each(function () {450            var options = $(this)451                , select = options.data('selectBox-select')452                , control = select.data('selectBox-control')453                , settings = select.data('selectBox-settings');454            if (select.triggerHandler('beforeclose')) {455                return false;456            }457            var dispatchCloseEvent = function () {458                select.triggerHandler('close', {459                    _selectBox: true460                });461            };462            if (settings) {463                switch (settings.menuTransition) {464                    case 'fade':465                        options.fadeOut(settings.menuSpeed, dispatchCloseEvent);466                        break;467                    case 'slide':468                        options.slideUp(settings.menuSpeed, dispatchCloseEvent);469                        break;470                    default:471                        options.hide(settings.menuSpeed, dispatchCloseEvent);472                        break;473                }474                if (!settings.menuSpeed) {475                    dispatchCloseEvent();476                }477                control.removeClass('selectBox-menuShowing');478            } else {479                $(this).hide();480                $(this).triggerHandler('close', {481                    _selectBox: true482                });483                $(this).removeClass('selectBox-menuShowing');484            }485        });486    };487    /**488     * Selects an option.489     *490     * @param {HTMLElement} li491     * @param {DOMEvent}    event492     * @returns {Boolean}493     */494    SelectBox.prototype.selectOption = function (li, event) {495        var select = $(this.selectElement);496        li         = $(li);497        var control    = select.data('selectBox-control')498            , settings = select.data('selectBox-settings');499        if (control.hasClass('selectBox-disabled')) {500            return false;501        }502        if (0 === li.length || li.hasClass('selectBox-disabled')) {503            return false;504        }505        if (select.attr('multiple')) {506            // If event.shiftKey is true, this will select all options between li and the last li selected507            if (event.shiftKey && control.data('selectBox-last-selected')) {508                li.toggleClass('selectBox-selected');509                var affectedOptions;510                if (li.index() > control.data('selectBox-last-selected').index()) {511                    affectedOptions = li512                        .siblings()513                        .slice(control.data('selectBox-last-selected').index(), li.index());514                } else {515                    affectedOptions = li516                        .siblings()517                        .slice(li.index(), control.data('selectBox-last-selected').index());518                }519                affectedOptions = affectedOptions.not('.selectBox-optgroup, .selectBox-disabled');520                if (li.hasClass('selectBox-selected')) {521                    affectedOptions.addClass('selectBox-selected');522                } else {523                    affectedOptions.removeClass('selectBox-selected');524                }525            } else if ((this.isMac && event.metaKey) || (!this.isMac && event.ctrlKey)) {526                li.toggleClass('selectBox-selected');527            } else {528                li.siblings().removeClass('selectBox-selected');529                li.addClass('selectBox-selected');530            }531        } else {532            li.siblings().removeClass('selectBox-selected');533            li.addClass('selectBox-selected');534        }535        if (control.hasClass('selectBox-dropdown')) {536            control.find('.selectBox-label').text(li.text());537        }538        // Update original control's value539        var i = 0, selection = [];540        if (select.attr('multiple')) {541            control.find('.selectBox-selected A').each(function () {542                selection[i++] = $(this).attr('rel');543            });544        } else {545            selection = li.find('A').attr('rel');546        }547        // Remember most recently selected item548        control.data('selectBox-last-selected', li);549        // Change callback550        if (select.val() !== selection) {551            select.val(selection);552            this.setLabel();553            select.trigger('change');554        }555        return true;556    };557    /**558     * Adds the hover class.559     *560     * @param {HTMLElement} li561     */562    SelectBox.prototype.addHover = function (li) {563        li = $(li);564        var select = $(this.selectElement)565            , control   = select.data('selectBox-control')566            , options = control.data('selectBox-options');567        options.find('.selectBox-hover').removeClass('selectBox-hover');568        li.addClass('selectBox-hover');569    };570    /**571     * Returns the original HTML select element.572     *573     * @returns {HTMLElement}574     */575    SelectBox.prototype.getSelectElement = function () {576        return this.selectElement;577    };578    /**579     * Remove the hover class.580     *581     * @param {HTMLElement} li582     */583    SelectBox.prototype.removeHover = function (li) {584        li = $(li);585        var select = $(this.selectElement)586            , control = select.data('selectBox-control')587            , options = control.data('selectBox-options');588        options.find('.selectBox-hover').removeClass('selectBox-hover');589    };590    /**591     * Checks if the widget is in the view.592     *593     * @param {jQuery}      li594     * @param {Boolean}     center595     */596    SelectBox.prototype.keepOptionInView = function (li, center) {597        if (!li || li.length === 0) {598            return;599        }600        var select = $(this.selectElement)601            , control     = select.data('selectBox-control')602            , options   = control.data('selectBox-options')603            , scrollBox = control.hasClass('selectBox-dropdown') ? options : options.parent()604            , top       = parseInt(li.offset().top -scrollBox.position().top)605            , bottom    = parseInt(top + li.outerHeight());606        if (center) {607            scrollBox.scrollTop(li.offset().top - scrollBox.offset().top + scrollBox.scrollTop() -608                (scrollBox.height() / 2));609        } else {610            if (top < 0) {611                scrollBox.scrollTop(li.offset().top - scrollBox.offset().top + scrollBox.scrollTop());612            }613            if (bottom > scrollBox.height()) {614                scrollBox.scrollTop((li.offset().top + li.outerHeight()) - scrollBox.offset().top +615                    scrollBox.scrollTop() - scrollBox.height());616            }617        }618    };619    /**620     * Handles the keyDown event.621     * Handles open/close and arrow key functionality622     *623     * @param {DOMEvent}    event624     */625    SelectBox.prototype.handleKeyDown = function (event) {626        var select = $(this.selectElement)627            , control        = select.data('selectBox-control')628            , options      = control.data('selectBox-options')629            , settings     = select.data('selectBox-settings')630            , totalOptions = 0, i = 0;631        if (control.hasClass('selectBox-disabled')) {632            return;633        }634        switch (event.keyCode) {635            case 8:636                // backspace637                event.preventDefault();638                this.typeSearch = '';639                break;640            case 9:641            // tab642            case 27:643                // esc644                this.hideMenus();645                this.removeHover();646                break;647            case 13:648                // enter649                if (control.hasClass('selectBox-menuShowing')) {650                    this.selectOption(options.find('LI.selectBox-hover:first'), event);651                    if (control.hasClass('selectBox-dropdown')) {652                        this.hideMenus();653                    }654                } else {655                    this.showMenu();656                }657                break;658            case 38:659            // up660            case 37:661                // left662                event.preventDefault();663                if (control.hasClass('selectBox-menuShowing')) {664                    var prev = options.find('.selectBox-hover').prev('LI');665                    totalOptions = options.find('LI:not(.selectBox-optgroup)').length;666                    i = 0;667                    while (prev.length === 0 || prev.hasClass('selectBox-disabled') ||668                        prev.hasClass('selectBox-optgroup')) {669                        prev = prev.prev('LI');670                        if (prev.length === 0) {671                            if (settings.loopOptions) {672                                prev = options.find('LI:last');673                            } else {674                                prev = options.find('LI:first');675                            }676                        }677                        if (++i >= totalOptions) {678                            break;679                        }680                    }681                    this.addHover(prev);682                    this.selectOption(prev, event);683                    this.keepOptionInView(prev);684                } else {685                    this.showMenu();686                }687                break;688            case 40:689            // down690            case 39:691                // right692                event.preventDefault();693                if (control.hasClass('selectBox-menuShowing')) {694                    var next = options.find('.selectBox-hover').next('LI');695                    totalOptions = options.find('LI:not(.selectBox-optgroup)').length;696                    i = 0;697                    while (0 === next.length || next.hasClass('selectBox-disabled') ||698                        next.hasClass('selectBox-optgroup')) {699                        next = next.next('LI');700                        if (next.length === 0) {701                            if (settings.loopOptions) {702                                next = options.find('LI:first');703                            } else {704                                next = options.find('LI:last');705                            }706                        }707                        if (++i >= totalOptions) {708                            break;709                        }710                    }711                    this.addHover(next);712                    this.selectOption(next, event);713                    this.keepOptionInView(next);714                } else {715                    this.showMenu();716                }717                break;718        }719    };720    /**721     * Handles the keyPress event.722     * Handles type-to-find functionality723     *724     * @param {DOMEvent}    event725     */726    SelectBox.prototype.handleKeyPress = function (event) {727        var select = $(this.selectElement)728            , control = select.data('selectBox-control')729            , options = control.data('selectBox-options');730        if (control.hasClass('selectBox-disabled')) {731            return;732        }733        switch (event.keyCode) {734            case 9:735            // tab736            case 27:737            // esc738            case 13:739            // enter740            case 38:741            // up742            case 37:743            // left744            case 40:745            // down746            case 39:747                // right748                // Don't interfere with the keydown event!749                break;750            default:751                // Type to find752                if (!control.hasClass('selectBox-menuShowing')) {753                    this.showMenu();754                }755                event.preventDefault();756                clearTimeout(this.typeTimer);757                this.typeSearch += String.fromCharCode(event.charCode || event.keyCode);758                options.find('A').each(function () {759                    if ($(this).text().substr(0, this.typeSearch.length).toLowerCase() === this.typeSearch.toLowerCase()) {760                        this.addHover($(this).parent());761                        this.selectOption($(this).parent(), event);762                        this.keepOptionInView($(this).parent());763                        return false;764                    }765                });766                // Clear after a brief pause767                this.typeTimer = setTimeout(function () {768                    this.typeSearch = '';769                }, 1000);770                break;771        }772    };773    /**774     * Enables the selectBox.775     */776    SelectBox.prototype.enable = function () {777        var select = $(this.selectElement);778        select.prop('disabled', false);779        var control = select.data('selectBox-control');780        if (!control) {781            return;782        }783        control.removeClass('selectBox-disabled');784    };785    /**786     * Disables the selectBox.787     */788    SelectBox.prototype.disable = function () {789        var select = $(this.selectElement);790        select.prop('disabled', true);791        var control = select.data('selectBox-control');792        if (!control) {793            return;794        }795        control.addClass('selectBox-disabled');796    };797    /**798     * Sets the current value.799     *800     * @param {String}      value801     */802    SelectBox.prototype.setValue = function (value) {803        var select = $(this.selectElement);804        select.val(value);805        value = select.val(); // IE9's select would be null if it was set with a non-exist options value806        if (null === value) { // So check it here and set it with the first option's value if possible807            value = select.children().first().val();808            select.val(value);809        }810        var control = select.data('selectBox-control');811        if (!control) {812            return;813        }814        var settings = select.data('selectBox-settings')815            , options = control.data('selectBox-options');816        // Update label817        this.setLabel();818        // Update control values819        options.find('.selectBox-selected').removeClass('selectBox-selected');820        options.find('A').each(function () {821            if (typeof(value) === 'object') {822                for (var i = 0; i < value.length; i++) {823                    if ($(this).attr('rel') == value[i]) {824                        $(this).parent().addClass('selectBox-selected');825                    }826                }827            } else {828                if ($(this).attr('rel') == value) {829                    $(this).parent().addClass('selectBox-selected');830                }831            }832        });833        if (settings.change) {834            settings.change.call(select);835        }836    };837    /**838     * Sets the option elements.839     *840     * @param {String|Object} options841     */842    SelectBox.prototype.setOptions = function (options) {843        var select = $(this.selectElement)844            , control = select.data('selectBox-control')845            , settings = select.data('selectBox-settings')846            , type;847        switch (typeof(options)) {848            case 'string':849                select.html(options);850                break;851            case 'object':852                select.html('');853                for (var i in options) {854                    if (options[i] === null) {855                        continue;856                    }857                    if (typeof(options[i]) === 'object') {858                        var optgroup = $('<optgroup label="' + i + '" />');859                        for (var j in options[i]) {860                            optgroup.append('<option value="' + j + '">' + options[i][j] + '</option>');861                        }862                        select.append(optgroup);863                    } else {864                        var option = $('<option value="' + i + '">' + options[i] + '</option>');865                        select.append(option);866                    }867                }868                break;869        }870        if (!control) {871            return;872        }873        // Remove old options874        control.data('selectBox-options').remove();875        // Generate new options876        type     = control.hasClass('selectBox-dropdown') ? 'dropdown' : 'inline';877        options  = this.getOptions(type);878        control.data('selectBox-options', options);879        switch (type) {880            case 'inline':881                control.append(options);882                break;883            case 'dropdown':884                // Update label885                this.setLabel();886                $("BODY").append(options);887                break;888        }889    };890    /**891     * Disables the selection.892     *893     * @param {*} selector894     */895    SelectBox.prototype.disableSelection = function (selector) {896        $(selector).css('MozUserSelect', 'none').bind('selectstart', function (event) {897            event.preventDefault();898        });899    };900    /**901     * Generates the options.902     *903     * @param {jQuery} self904     * @param {jQuery} options905     */906    SelectBox.prototype.generateOptions = function (self, options) {907        var li = $('<li />'), a = $('<a />');908        li.addClass(self.attr('class'));909        li.data(self.data());910        a.attr('rel', self.val()).text(self.text());911        li.append(a);912        if (self.attr('disabled')) {913            li.addClass('selectBox-disabled');914        }915        if (self.attr('selected')) {916            li.addClass('selectBox-selected');917        }918        options.append(li);919    };920    /**921     * Extends the jQuery.fn object.922     */923    $.extend($.fn, {924        selectBox: function (method, options) {925            var selectBox;926            switch (method) {927                case 'control':928                    return $(this).data('selectBox-control');929                case 'settings':930                    if (!options) {931                        return $(this).data('selectBox-settings');932                    }933                    $(this).each(function () {934                        $(this).data('selectBox-settings', $.extend(true, $(this).data('selectBox-settings'), options));935                    });936                    break;937                case 'options':938                    // Getter939                    if (undefined === options) {940                        return $(this).data('selectBox-control').data('selectBox-options');941                    }942                    // Setter943                    $(this).each(function () {944                        if (selectBox = $(this).data('selectBox')) {945                            selectBox.setOptions(options);946                        }947                    });948                    break;949                case 'value':950                    // Empty string is a valid value951                    if (undefined === options) {952                        return $(this).val();953                    }954                    $(this).each(function () {955                        if (selectBox = $(this).data('selectBox')) {956                            selectBox.setValue(options);957                        }958                    });959                    break;960                case 'refresh':961                    $(this).each(function () {962                        if (selectBox = $(this).data('selectBox')) {963                            selectBox.refresh();964                        }965                    });966                    break;967                case 'enable':968                    $(this).each(function () {969                        if (selectBox = $(this).data('selectBox')) {970                            selectBox.enable(this);971                        }972                    });973                    break;974                case 'disable':975                    $(this).each(function () {976                        if (selectBox = $(this).data('selectBox')) {977                            selectBox.disable();978                        }979                    });980                    break;981                case 'destroy':982                    $(this).each(function () {983                        if (selectBox = $(this).data('selectBox')) {984                            selectBox.destroy();985                            $(this).data('selectBox', null);986                        }987                    });988                    break;989                case 'instance':990                    return $(this).data('selectBox');991                default:992                    $(this).each(function (idx, select) {993                        if (!$(select).data('selectBox')) {994                            $(select).data('selectBox', new SelectBox(select, method));995                        }996                    });997                    break;998            }999            return $(this);1000        }1001    });...closure_i18n_ordinalrules.js
Source:closure_i18n_ordinalrules.js  
1// Copyright 2012 The Closure Library Authors. All Rights Reserved2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the12// License for the specific language governing permissions and limitations under13// the License.14/**15 * @fileoverview Ordinal rules.16 *17 * This file is autogenerated by script:18 *   http://go/generate_pluralrules.py19 * File generated from CLDR ver. 2320 *21 * Before check in, this file could have been manually edited. This is to22 * incorporate changes before we could fix CLDR. All manual modification must be23 * documented in this section, and should be removed after those changes land to24 * CLDR.25 */26goog.provide('goog.i18n.ordinalRules');27/**28 * Ordinal pattern keyword29 * @enum {string}30 */31goog.i18n.ordinalRules.Keyword = {32  ZERO: 'zero',33  ONE: 'one',34  TWO: 'two',35  FEW: 'few',36  MANY: 'many',37  OTHER: 'other'38};39/**40 * Default ordinal select rule.41 * @param {number} n The count of items.42 * @return {goog.i18n.ordinalRules.Keyword} Default value.43 * @private44 */45goog.i18n.ordinalRules.defaultSelect_ = function(n) {46  return goog.i18n.ordinalRules.Keyword.OTHER;47};48/**49 * Ordinal select rules for fr locale50 *51 * @param {number} n  The count of items.52 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.53 * @private54 */55goog.i18n.ordinalRules.frSelect_ = function(n) {56  if (n == 1) {57    return goog.i18n.ordinalRules.Keyword.ONE;58  }59  return goog.i18n.ordinalRules.Keyword.OTHER;60};61/**62 * Ordinal select rules for hu locale63 *64 * @param {number} n  The count of items.65 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.66 * @private67 */68goog.i18n.ordinalRules.huSelect_ = function(n) {69  if (n == 1 || n == 5) {70    return goog.i18n.ordinalRules.Keyword.ONE;71  }72  return goog.i18n.ordinalRules.Keyword.OTHER;73};74/**75 * Ordinal select rules for sv locale76 *77 * @param {number} n  The count of items.78 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.79 * @private80 */81goog.i18n.ordinalRules.svSelect_ = function(n) {82  if ((n % 10 == 1 || n % 10 == 2) && n % 100 != 11 && n % 100 != 12) {83    return goog.i18n.ordinalRules.Keyword.ONE;84  }85  return goog.i18n.ordinalRules.Keyword.OTHER;86};87/**88 * Ordinal select rules for en locale89 *90 * @param {number} n  The count of items.91 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.92 * @private93 */94goog.i18n.ordinalRules.enSelect_ = function(n) {95  if (n % 10 == 1 && n % 100 != 11) {96    return goog.i18n.ordinalRules.Keyword.ONE;97  }98  if (n % 10 == 2 && n % 100 != 12) {99    return goog.i18n.ordinalRules.Keyword.TWO;100  }101  if (n % 10 == 3 && n % 100 != 13) {102    return goog.i18n.ordinalRules.Keyword.FEW;103  }104  return goog.i18n.ordinalRules.Keyword.OTHER;105};106/**107 * Ordinal select rules for it locale108 *109 * @param {number} n  The count of items.110 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.111 * @private112 */113goog.i18n.ordinalRules.itSelect_ = function(n) {114  if (n == 11 || n == 8 || n == 80 || n == 800) {115    return goog.i18n.ordinalRules.Keyword.MANY;116  }117  return goog.i18n.ordinalRules.Keyword.OTHER;118};119/**120 * Ordinal select rules for ca locale121 *122 * @param {number} n  The count of items.123 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.124 * @private125 */126goog.i18n.ordinalRules.caSelect_ = function(n) {127  if (n == 1 || n == 3) {128    return goog.i18n.ordinalRules.Keyword.ONE;129  }130  if (n == 2) {131    return goog.i18n.ordinalRules.Keyword.TWO;132  }133  if (n == 4) {134    return goog.i18n.ordinalRules.Keyword.FEW;135  }136  return goog.i18n.ordinalRules.Keyword.OTHER;137};138/**139 * Ordinal select rules for mr locale140 *141 * @param {number} n  The count of items.142 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.143 * @private144 */145goog.i18n.ordinalRules.mrSelect_ = function(n) {146  if (n == 1) {147    return goog.i18n.ordinalRules.Keyword.ONE;148  }149  if (n == 2 || n == 3) {150    return goog.i18n.ordinalRules.Keyword.TWO;151  }152  if (n == 4) {153    return goog.i18n.ordinalRules.Keyword.FEW;154  }155  return goog.i18n.ordinalRules.Keyword.OTHER;156};157/**158 * Ordinal select rules for gu locale159 *160 * @param {number} n  The count of items.161 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.162 * @private163 */164goog.i18n.ordinalRules.guSelect_ = function(n) {165  if (n == 1) {166    return goog.i18n.ordinalRules.Keyword.ONE;167  }168  if (n == 2 || n == 3) {169    return goog.i18n.ordinalRules.Keyword.TWO;170  }171  if (n == 4) {172    return goog.i18n.ordinalRules.Keyword.FEW;173  }174  if (n == 6) {175    return goog.i18n.ordinalRules.Keyword.MANY;176  }177  return goog.i18n.ordinalRules.Keyword.OTHER;178};179/**180 * Ordinal select rules for bn locale181 *182 * @param {number} n  The count of items.183 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.184 * @private185 */186goog.i18n.ordinalRules.bnSelect_ = function(n) {187  if (n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10) {188    return goog.i18n.ordinalRules.Keyword.ONE;189  }190  if (n == 2 || n == 3) {191    return goog.i18n.ordinalRules.Keyword.TWO;192  }193  if (n == 4) {194    return goog.i18n.ordinalRules.Keyword.FEW;195  }196  if (n == 6) {197    return goog.i18n.ordinalRules.Keyword.MANY;198  }199  return goog.i18n.ordinalRules.Keyword.OTHER;200};201/**202 * Ordinal select rules for zu locale203 *204 * @param {number} n  The count of items.205 * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.206 * @private207 */208goog.i18n.ordinalRules.zuSelect_ = function(n) {209  if (n == 1) {210    return goog.i18n.ordinalRules.Keyword.ONE;211  }212  if (n == (n | 0) && n >= 2 && n <= 9) {213    return goog.i18n.ordinalRules.Keyword.FEW;214  }215  if (n == (n | 0) && (n >= 10 && n <= 19 || n >= 100 && n <= 199 || n >= 1000 && n <= 1999)) {216    return goog.i18n.ordinalRules.Keyword.MANY;217  }218  return goog.i18n.ordinalRules.Keyword.OTHER;219};220/**221 * Selected ordinal rules by locale.222 */223goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;224if (goog.LOCALE == 'af') {225  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;226}227if (goog.LOCALE == 'am') {228  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;229}230if (goog.LOCALE == 'ar') {231  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;232}233if (goog.LOCALE == 'bg') {234  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;235}236if (goog.LOCALE == 'bn') {237  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.bnSelect_;238}239if (goog.LOCALE == 'br') {240  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;241}242if (goog.LOCALE == 'ca') {243  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.caSelect_;244}245if (goog.LOCALE == 'chr') {246  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;247}248if (goog.LOCALE == 'cs') {249  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;250}251if (goog.LOCALE == 'cy') {252  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;253}254if (goog.LOCALE == 'da') {255  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;256}257if (goog.LOCALE == 'de') {258  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;259}260if (goog.LOCALE == 'de_AT' || goog.LOCALE == 'de-AT') {261  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;262}263if (goog.LOCALE == 'de_CH' || goog.LOCALE == 'de-CH') {264  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;265}266if (goog.LOCALE == 'el') {267  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;268}269if (goog.LOCALE == 'en') {270  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;271}272if (goog.LOCALE == 'en_AU' || goog.LOCALE == 'en-AU') {273  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;274}275if (goog.LOCALE == 'en_GB' || goog.LOCALE == 'en-GB') {276  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;277}278if (goog.LOCALE == 'en_IE' || goog.LOCALE == 'en-IE') {279  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;280}281if (goog.LOCALE == 'en_IN' || goog.LOCALE == 'en-IN') {282  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;283}284if (goog.LOCALE == 'en_SG' || goog.LOCALE == 'en-SG') {285  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;286}287if (goog.LOCALE == 'en_US' || goog.LOCALE == 'en-US') {288  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;289}290if (goog.LOCALE == 'en_ZA' || goog.LOCALE == 'en-ZA') {291  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;292}293if (goog.LOCALE == 'es') {294  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;295}296if (goog.LOCALE == 'es_419' || goog.LOCALE == 'es-419') {297  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;298}299if (goog.LOCALE == 'es_ES' || goog.LOCALE == 'es-ES') {300  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;301}302if (goog.LOCALE == 'et') {303  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;304}305if (goog.LOCALE == 'eu') {306  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;307}308if (goog.LOCALE == 'fa') {309  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;310}311if (goog.LOCALE == 'fi') {312  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;313}314if (goog.LOCALE == 'fil') {315  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;316}317if (goog.LOCALE == 'fr') {318  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;319}320if (goog.LOCALE == 'fr_CA' || goog.LOCALE == 'fr-CA') {321  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;322}323if (goog.LOCALE == 'gl') {324  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;325}326if (goog.LOCALE == 'gsw') {327  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;328}329if (goog.LOCALE == 'gu') {330  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_;331}332if (goog.LOCALE == 'haw') {333  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;334}335if (goog.LOCALE == 'he') {336  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;337}338if (goog.LOCALE == 'hi') {339  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_;340}341if (goog.LOCALE == 'hr') {342  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;343}344if (goog.LOCALE == 'hu') {345  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.huSelect_;346}347if (goog.LOCALE == 'id') {348  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;349}350if (goog.LOCALE == 'in') {351  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;352}353if (goog.LOCALE == 'is') {354  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;355}356if (goog.LOCALE == 'it') {357  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.itSelect_;358}359if (goog.LOCALE == 'iw') {360  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;361}362if (goog.LOCALE == 'ja') {363  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;364}365if (goog.LOCALE == 'kn') {366  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;367}368if (goog.LOCALE == 'ko') {369  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;370}371if (goog.LOCALE == 'ln') {372  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;373}374if (goog.LOCALE == 'lt') {375  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;376}377if (goog.LOCALE == 'lv') {378  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;379}380if (goog.LOCALE == 'ml') {381  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;382}383if (goog.LOCALE == 'mr') {384  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.mrSelect_;385}386if (goog.LOCALE == 'ms') {387  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;388}389if (goog.LOCALE == 'mt') {390  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;391}392if (goog.LOCALE == 'nb') {393  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;394}395if (goog.LOCALE == 'nl') {396  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;397}398if (goog.LOCALE == 'no') {399  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;400}401if (goog.LOCALE == 'or') {402  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;403}404if (goog.LOCALE == 'pl') {405  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;406}407if (goog.LOCALE == 'pt') {408  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;409}410if (goog.LOCALE == 'pt_BR' || goog.LOCALE == 'pt-BR') {411  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;412}413if (goog.LOCALE == 'pt_PT' || goog.LOCALE == 'pt-PT') {414  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;415}416if (goog.LOCALE == 'ro') {417  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;418}419if (goog.LOCALE == 'ru') {420  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;421}422if (goog.LOCALE == 'sk') {423  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;424}425if (goog.LOCALE == 'sl') {426  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;427}428if (goog.LOCALE == 'sq') {429  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;430}431if (goog.LOCALE == 'sr') {432  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;433}434if (goog.LOCALE == 'sv') {435  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.svSelect_;436}437if (goog.LOCALE == 'sw') {438  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;439}440if (goog.LOCALE == 'ta') {441  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;442}443if (goog.LOCALE == 'te') {444  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;445}446if (goog.LOCALE == 'th') {447  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;448}449if (goog.LOCALE == 'tl') {450  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;451}452if (goog.LOCALE == 'tr') {453  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;454}455if (goog.LOCALE == 'uk') {456  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;457}458if (goog.LOCALE == 'ur') {459  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;460}461if (goog.LOCALE == 'vi') {462  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;463}464if (goog.LOCALE == 'zh') {465  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;466}467if (goog.LOCALE == 'zh_CN' || goog.LOCALE == 'zh-CN') {468  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;469}470if (goog.LOCALE == 'zh_HK' || goog.LOCALE == 'zh-HK') {471  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;472}473if (goog.LOCALE == 'zh_TW' || goog.LOCALE == 'zh-TW') {474  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;475}476if (goog.LOCALE == 'zu') {477  goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.zuSelect_;...jquery.cxselect.js
Source:jquery.cxselect.js  
1/*!2 * jQuery cxSelect3 * @name jquery.cxselect.js4 * @version 1.4.25 * @date 2017-09-266 * @author ciaoca7 * @email ciaoca@gmail.com8 * @site https://github.com/ciaoca/cxSelect9 * @license Released under the MIT license10 */11(function(factory) {12  if (typeof define === 'function' && define.amd) {13    define(['jquery'], factory);14  } else {15    factory(window.jQuery || window.Zepto || window.$);16  };17}(function($) {18  var cxSelect = function() {19    var self = this;20    var dom, settings, callback;2122    // åé
åæ°23    for (var i = 0, l = arguments.length; i < l; i++) {24      if (cxSelect.isJquery(arguments[i]) || cxSelect.isZepto(arguments[i])) {25        dom = arguments[i];26      } else if (cxSelect.isElement(arguments[i])) {27        dom = $(arguments[i]);28      } else if (typeof arguments[i] === 'function') {29        callback = arguments[i];30      } else if (typeof arguments[i] === 'object') {31        settings = arguments[i];32      };33    };3435    var api = new cxSelect.init(dom, settings);3637    if (typeof callback === 'function') {38      callback(api);39    };4041    return api;42  };4344  cxSelect.isElement = function(o){45    if (o && (typeof HTMLElement === 'function' || typeof HTMLElement === 'object') && o instanceof HTMLElement) {46      return true;47    } else {48      return (o && o.nodeType && o.nodeType === 1) ? true : false;49    };50  };5152  cxSelect.isJquery = function(o){53    return (o && o.length && (typeof jQuery === 'function' || typeof jQuery === 'object') && o instanceof jQuery) ? true : false;54  };5556  cxSelect.isZepto = function(o){57    return (o && o.length && (typeof Zepto === 'function' || typeof Zepto === 'object') && Zepto.zepto.isZ(o)) ? true : false;58  };5960  cxSelect.getIndex = function(n, required) {61    return required ? n : n - 1;62  };6364  cxSelect.getData = function(data, space) {65    if (typeof space === 'string' && space.length) {66      space = space.split('.');67      for (var i = 0, l = space.length; i < l; i++) {68        data = data[space[i]];69      };70    };71    return data;72  };7374  cxSelect.init = function(dom, settings) {75    var self = this;7677    if (!cxSelect.isJquery(dom) && !cxSelect.isZepto(dom)) {return};7879    var theSelect = {80      dom: {81        box: dom82      }83    };8485    self.attach = cxSelect.attach.bind(theSelect);86    self.detach = cxSelect.detach.bind(theSelect);87    self.setOptions = cxSelect.setOptions.bind(theSelect);88    self.clear = cxSelect.clear.bind(theSelect);8990    theSelect.changeEvent = function() {91      cxSelect.selectChange.call(theSelect, this.className);92    };9394    theSelect.settings = $.extend({}, $.cxSelect.defaults, settings, {95      url: theSelect.dom.box.data('url'),96      emptyStyle: theSelect.dom.box.data('emptyStyle'),97      required: theSelect.dom.box.data('required'),98      firstTitle: theSelect.dom.box.data('firstTitle'),99      firstValue: theSelect.dom.box.data('firstValue'),100      jsonSpace: theSelect.dom.box.data('jsonSpace'),101      jsonName: theSelect.dom.box.data('jsonName'),102      jsonValue: theSelect.dom.box.data('jsonValue'),103      jsonSub: theSelect.dom.box.data('jsonSub')104    });105106    var _dataSelects = theSelect.dom.box.data('selects');107108    if (typeof _dataSelects === 'string' && _dataSelects.length) {109      theSelect.settings.selects = _dataSelects.split(',');110    };111112    self.setOptions();113    self.attach();114115    // 使ç¨ç¬ç«æ¥å£è·åæ°æ®116    if (!theSelect.settings.url && !theSelect.settings.data) {117      cxSelect.start.apply(theSelect);118119    // 设置èªå®ä¹æ°æ®120    } else if ($.isArray(theSelect.settings.data)) {121      cxSelect.start.call(theSelect, theSelect.settings.data);122123    // 设置 URLï¼éè¿ Ajax è·åæ°æ®124    } else if (typeof theSelect.settings.url === 'string' && theSelect.settings.url.length) {125      $.getJSON(theSelect.settings.url, function(json) {126        cxSelect.start.call(theSelect, json);127      });128    };129  };130131  // è®¾ç½®åæ°132  cxSelect.setOptions = function(opts) {133    var self = this;134135    if (opts) {136      $.extend(self.settings, opts);137    };138139    // 忬¡æéè®¾éæ©å¨ç»140    if (!$.isArray(self.selectArray) || !self.selectArray.length || (opts && opts.selects)) {141      self.selectArray = [];142143      if ($.isArray(self.settings.selects) && self.settings.selects.length) {144        var _tempSelect;145146        for (var i = 0, l = self.settings.selects.length; i < l; i++) {147          _tempSelect = self.dom.box.find('select.' + self.settings.selects[i]);148149          if (!_tempSelect || !_tempSelect.length) {break};150151          self.selectArray.push(_tempSelect);152        };153      };154    };155156    if (opts) {157      if (!$.isArray(opts.data) && typeof opts.url === 'string' && opts.url.length) {158        $.getJSON(self.settings.url, function(json) {159          cxSelect.start.call(self, json);160        });161162      } else {163        cxSelect.start.call(self, opts.data);164      };165    };166  };167168  // ç»å®169  cxSelect.attach = function() {170    var self = this;171172    if (!self.attachStatus) {173      self.dom.box.on('change', 'select', self.changeEvent);174    };175176    if (typeof self.attachStatus === 'boolean') {177      cxSelect.start.call(self);178    };179180    self.attachStatus = true;181  };182183  // ç§»é¤ç»å®184  cxSelect.detach = function() {185    var self = this;186    self.dom.box.off('change', 'select', self.changeEvent);187    self.attachStatus = false;188  };189190  // æ¸
空é项191  cxSelect.clear = function(index) {192    var self = this;193    var _style = {194      display: '',195      visibility: ''196    };197198    index = isNaN(index) ? 0 : index;199200    // æ¸
空åé¢ç select201    for (var i = index, l = self.selectArray.length; i < l; i++) {202      self.selectArray[i].empty().prop('disabled', true);203204      if (self.settings.emptyStyle === 'none') {205        _style.display = 'none';206      } else if (self.settings.emptyStyle === 'hidden') {207        _style.visibility = 'hidden';208      };209210      self.selectArray[i].css(_style);211    };212  };213214  cxSelect.start = function(data) {215    var self = this;216217    if ($.isArray(data)) {218      self.settings.data = cxSelect.getData(data, self.settings.jsonSpace);219    };220221    if (!self.selectArray.length) {return};222223    // ä¿åé»è®¤å¼224    for (var i = 0, l = self.selectArray.length; i < l; i++) {225      if (typeof self.selectArray[i].attr('data-value') !== 'string' && self.selectArray[i][0].options.length) {226        self.selectArray[i].attr('data-value', self.selectArray[i].val());227      };228    };229230    if (self.settings.data || (typeof self.selectArray[0].data('url') === 'string' && self.selectArray[0].data('url').length)) {231      cxSelect.getOptionData.call(self, 0);232    } else if (self.selectArray[0][0].options.length && typeof self.selectArray[0].attr('data-value') === 'string' && self.selectArray[0].attr('data-value').length) {233      self.selectArray[0].val(self.selectArray[0].attr('data-value'));234      cxSelect.getOptionData.call(self, 1);235    } else {236      self.selectArray[0].prop('disabled', false).css({237        'display': '',238        'visibility': ''239      });240    };241  };242243  // è·åéé¡¹æ°æ®244  cxSelect.getOptionData = function(index) {245    var self = this;246247    if (typeof index !== 'number' || isNaN(index) || index < 0 || index >= self.selectArray.length) {return};248249    var _indexPrev = index - 1;250    var _select = self.selectArray[index];251    var _selectData;252    var _valueIndex;253    var _dataUrl = _select.data('url');254    var _jsonSpace = typeof _select.data('jsonSpace') === 'undefined' ? self.settings.jsonSpace : _select.data('jsonSpace');255    var _query = {};256    var _queryName;257    var _selectName;258    var _selectValue;259260    cxSelect.clear.call(self, index);261262    // 使ç¨ç¬ç«æ¥å£263    if (typeof _dataUrl === 'string' && _dataUrl.length) {264      if (index > 0) {265        for (var i = 0, j = 1; i < index; i++, j++) {266          _queryName = self.selectArray[j].data('queryName');267          _selectName = self.selectArray[i].attr('name');268          _selectValue = self.selectArray[i].val();269270          if (typeof _queryName === 'string' && _queryName.length) {271            _query[_queryName] = _selectValue;272          } else if (typeof _selectName === 'string' && _selectName.length) {273            _query[_selectName] = _selectValue;274          };275        };276      };277278      $.getJSON(_dataUrl, _query, function(json) {279        _selectData = cxSelect.getData(json, _jsonSpace);280281        cxSelect.buildOption.call(self, index, _selectData);282      });283284    // ä½¿ç¨æ´åæ°æ®285    } else if (self.settings.data && typeof self.settings.data === 'object') {286      _selectData = self.settings.data;287288      for (var i = 0; i < index; i++) {289        _valueIndex = cxSelect.getIndex(self.selectArray[i][0].selectedIndex, typeof self.selectArray[i].data('required') === 'boolean' ? self.selectArray[i].data('required') : self.settings.required);290291        if (typeof _selectData[_valueIndex] === 'object' && $.isArray(_selectData[_valueIndex][self.settings.jsonSub]) && _selectData[_valueIndex][self.settings.jsonSub].length) {292          _selectData = _selectData[_valueIndex][self.settings.jsonSub];293        } else {294          _selectData = null;295          break;296        };297      };298299      cxSelect.buildOption.call(self, index, _selectData);300    };301  };302303  // æå»ºé项å表304  cxSelect.buildOption = function(index, data) {305    var self = this;306307    var _select = self.selectArray[index];308    var _required = typeof _select.data('required') === 'boolean' ? _select.data('required') : self.settings.required;309    var _firstTitle = typeof _select.data('firstTitle') === 'undefined' ? self.settings.firstTitle : _select.data('firstTitle');310    var _firstValue = typeof _select.data('firstValue') === 'undefined' ? self.settings.firstValue : _select.data('firstValue');311    var _jsonName = typeof _select.data('jsonName') === 'undefined' ? self.settings.jsonName : _select.data('jsonName');312    var _jsonValue = typeof _select.data('jsonValue') === 'undefined' ? self.settings.jsonValue : _select.data('jsonValue');313314    if (!$.isArray(data)) {return};315316    var _html = !_required ? '<option value="' + String(_firstValue) + '">' + String(_firstTitle) + '</option>' : '';317318    // åºåæ é¢ãå¼çæ°æ®319    if (typeof _jsonName === 'string' && _jsonName.length) {320      // æ å¼å段æ¶ä½¿ç¨æ é¢ä½ä¸ºå¼321      if (typeof _jsonValue !== 'string' || !_jsonValue.length) {322        _jsonValue = _jsonName;323      };324325      for (var i = 0, l = data.length; i < l; i++) {326        _html += '<option value="' + String(data[i][_jsonValue]) + '">' + String(data[i][_jsonName]) + '</option>';327      };328329    // æ°ç»å³ä¸ºå¼çæ°æ®330    } else {331      for (var i = 0, l = data.length; i < l; i++) {332        _html += '<option value="' + String(data[i]) + '">' + String(data[i]) + '</option>';333      };334    };335336    _select.html(_html).prop('disabled', false).css({337      'display': '',338      'visibility': ''339    });340341    // 忬¡å è½½è®¾ç½®é»è®¤å¼342    if (typeof _select.attr('data-value') === 'string') {343      _select.val(String(_select.attr('data-value'))).removeAttr('data-value');344345      if (_select[0].selectedIndex < 0) {346        _select[0].options[0].selected = true;347      };348    };349350    if (_required || _select[0].selectedIndex > 0) {351      _select.trigger('change');352    };353354  };355356  // æ¹åéæ©æ¶çå¤ç357  cxSelect.selectChange = function(name) {358    var self = this;359360    if (typeof name !== 'string' || !name.length) {return};361362    var index;363364    name = name.replace(/\s+/g, ',');365    name = ',' + name + ',';366367    // è·åå½å select ä½ç½®368    for (var i = 0, l = self.selectArray.length; i < l; i++) {369      if (name.indexOf(',' + self.settings.selects[i] + ',') > -1) {370        index = i;371        break;372      };373    };374375    if (typeof index === 'number' && index > -1) {376      index += 1;377      cxSelect.getOptionData.call(self, index);378    };379  };380381  $.cxSelect = function() {382    return cxSelect.apply(this, arguments);383  };384385  // é»è®¤å¼386  $.cxSelect.defaults = {387    selects: [],            // 䏿鿡ç»388    url: null,              // åè¡¨æ°æ®æä»¶è·¯å¾ï¼URLï¼ææ°ç»æ°æ®389    data: null,             // èªå®ä¹æ°æ®390    emptyStyle: null,       // æ æ°æ®ç¶ææ¾ç¤ºæ¹å¼391    required: false,        // æ¯å¦ä¸ºå¿
é392    firstTitle: 'è¯·éæ©',    // 第ä¸ä¸ªéé¡¹çæ é¢393    firstValue: '',         // 第ä¸ä¸ªé项çå¼394    jsonSpace: '',          // æ°æ®å½å空é´395    jsonName: 'n',          // æ°æ®æ é¢å段åç§°396    jsonValue: '',          // æ°æ®å¼å段åç§°397    jsonSub: 's'            // åéæ°æ®å段åç§°398  };399400  $.fn.cxSelect = function(settings, callback) {401    this.each(function(i) {402      $.cxSelect(this, settings, callback);403    });404    return this;405  };
...select-tests.js
Source:select-tests.js  
...87test('select works for single', function (assert) {88  var $select = $('#qunit-fixture .single-with-placeholder');89  var data = new SelectData($select, selectOptions);90  assert.equal($select.val(), 'placeholder');91  data.select({92    id: 'One',93    text: 'One'94  });95  assert.equal($select.val(), 'One');96});97test('multiple sets the value', function (assert) {98  var $select = $('#qunit-fixture .multiple');99  var data = new SelectData($select, selectOptions);100  assert.equal($select.val(), null);101  data.select({102    id: 'Two',103    text: 'Two'104  });105  assert.deepEqual($select.val(), ['Two']);106});107test('multiple adds to the old value', function (assert) {108  var $select = $('#qunit-fixture .multiple');109  var data = new SelectData($select, selectOptions);110  $select.val(['Two']);111  assert.deepEqual($select.val(), ['Two']);112  data.select({113    id: 'One',114    text: 'One'115  });116  assert.deepEqual($select.val(), ['One', 'Two']);117});118test('duplicates - single - same id on select triggers change',119  function (assert) {120  var $select = $('#qunit-fixture .duplicates');121  var data = new SelectData($select, data);122  var second = $('#qunit-fixture .duplicates option')[2];123  var changeTriggered = false;124  assert.equal($select.val(), 'one');125  $select.on('change', function () {126    changeTriggered = true;127  });128  data.select({129    id: 'one',130    text: 'Uno',131    element: second132  });133  assert.equal(134    $select.val(),135    'one',136    'The value never changed'137  );138  assert.ok(139    changeTriggered,140    'The change event should be triggered'141  );142  assert.ok(143    second.selected,144    'The second duplicate is selected, not the first'145  );146});147test('duplicates - single - different id on select triggers change',148  function (assert) {149  var $select = $('#qunit-fixture .duplicates');150  var data = new SelectData($select, data);151  var second = $('#qunit-fixture .duplicates option')[2];152  var changeTriggered = false;153  $select.val('two');154  $select.on('change', function () {155    changeTriggered = true;156  });157  data.select({158    id: 'one',159    text: 'Uno',160    element: second161  });162  assert.equal(163    $select.val(),164    'one',165    'The value changed to the duplicate id'166  );167  assert.ok(168    changeTriggered,169    'The change event should be triggered'170  );171  assert.ok(172    second.selected,173    'The second duplicate is selected, not the first'174  );175});176test('duplicates - multiple - same id on select triggers change',177function (assert) {178  var $select = $('#qunit-fixture .duplicates-multi');179  var data = new SelectData($select, data);180  var second = $('#qunit-fixture .duplicates-multi option')[2];181  var changeTriggered = false;182  $select.val(['one']);183  $select.on('change', function () {184    changeTriggered = true;185  });186  data.select({187    id: 'one',188    text: 'Uno',189    element: second190  });191  assert.deepEqual(192    $select.val(),193    ['one', 'one'],194    'The value now has duplicates'195  );196  assert.ok(197    changeTriggered,198    'The change event should be triggered'199  );200  assert.ok(201    second.selected,202    'The second duplicate is selected, not the first'203  );204});205test('duplicates - multiple - different id on select triggers change',206function (assert) {207  var $select = $('#qunit-fixture .duplicates-multi');208  var data = new SelectData($select, data);209  var second = $('#qunit-fixture .duplicates-multi option')[2];210  var changeTriggered = false;211  $select.val(['two']);212  $select.on('change', function () {213    changeTriggered = true;214  });215  data.select({216    id: 'one',217    text: 'Uno',218    element: second219  });220  assert.deepEqual(221    $select.val(),222    ['two', 'one'],223    'The value has the new id'224  );225  assert.ok(226    changeTriggered,227    'The change event should be triggered'228  );229  assert.ok(...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
