Skip to content

Instantly share code, notes, and snippets.

@zonaro
Created July 23, 2019 16:11
Show Gist options
  • Save zonaro/806842266126fc39251d4b8a67f07ae5 to your computer and use it in GitHub Desktop.
Save zonaro/806842266126fc39251d4b8a67f07ae5 to your computer and use it in GitHub Desktop.
auto group option in optgroup by attribute
$.fn.autoGroup = function (selector) {
var elem = $(this);
let a = [];
selector = selector || "data-group";
elem.find("option").appendTo(elem); //remove options dentro de optgroups e coloca no select
elem.find("optgroup").remove(); // remove optgroups
elem.find("[" + selector + "]").each(function (index) {
a.push($(this).attr(selector));
});
var unique = a.filter(function (itm, i, a) {
return i == a.indexOf(itm);
});
for (var i = 0; i < unique.length; i++) {
if (unique[i].length > 0) {
elem.find("[" + selector + "='" + unique[i] + "']")
.wrapAll("<optgroup label='" + unique[i] + "'>");
}
}
elem.val(elem.find("[selected]").attr("value"));
elem.trigger("change");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment