Skip to content

Instantly share code, notes, and snippets.

@dkrnl
Last active September 7, 2016 07:37
Show Gist options
  • Save dkrnl/23dbfcb7336bbc45599b35a6aa9c852e to your computer and use it in GitHub Desktop.
Save dkrnl/23dbfcb7336bbc45599b35a6aa9c852e to your computer and use it in GitHub Desktop.
Selectize clear button
/**
* Plugin: "clear_button" (selectize.js)
* Copyright (c) 2015 Dmitri Piatkov & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Dmitri Piatkov <[email protected]>
*/
Selectize.define("clear_button", function(options) {
var self = this;
if (self.settings.mode === "multiple") {
return;
}
options = $.extend({
label : "<i class=\"fa fa-times\"></i>",
className : "btn btn-block btn-link",
append : true
}, options);
self.on("initialize", function() {
self.$clear_button = $("<button type=\"button\" tabindex=\"-1\"></button>");
self.$clear_button.addClass(options.className).html(options.label);
self.$clear_button.prop("disabled", !self.items.length);
self.$dropdown.prepend(self.$clear_button);
self.$clear_button.click(function() {
if (self.items.length) {
self.setValue("");
self.onChange();
self.close();
}
});
self.on("change", function() {
self.$clear_button.prop("disabled", !self.items.length);
});
});
});
@dkrnl
Copy link
Author

dkrnl commented Sep 7, 2016

Usage example:

$("select.form-control").each(function() {
        var select = $(this), options = {plugins: {}};
        if (select.prop("multiple")) {
            options.hideSelected = false;
            options.plugins["remove_button"] = {}; // default selectize pluging
            options.plugins["optgroup_checkbox"] = {}; // https://gist.github.com/dkrnl/c97099bd042d8180426b
        } else {
            options.plugins["clear_button"] = {}; // this plugin
        }
        options.allowEmptyOption = true;
        options = $.extend(true, {}, options, select.data());
        select.selectize(options);
 });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment