Skip to content

Instantly share code, notes, and snippets.

@Nemo64
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nemo64/9249376 to your computer and use it in GitHub Desktop.
Save Nemo64/9249376 to your computer and use it in GitHub Desktop.
automatically attaches select2 to all selects with the js-select2 class. All data-* attributes are passed as options to select2, eg. <select class="js-select2" data-minimum-input-length="3"></select>
// automatically attaches select2 to all selects with the js-select2 class
// All data-* attributes are passed as options to select2, eg. <select class="js-select2" data-minimum-input-length="3"></select>
// use the update event if you add new html (ajax etc.)
$(document).on("ready update", function (e) {
var $target = $(e.target);
$target.find("select.js-select2").each(function () {
var $select = $(this);
var options = $select.data();
for (var key in options) {
var option = options[key];
// allow functions
if (typeof option == "string" && option.substr(0, 11).toLowerCase() === "javascript:") {
option = new Function(option.substr(11));
option = $.proxy(option, this); // bind the original input
}
options[$.camelCase(key)] = option;
}
$select.select2(options);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment