Created
July 23, 2019 16:11
-
-
Save zonaro/806842266126fc39251d4b8a67f07ae5 to your computer and use it in GitHub Desktop.
auto group option in optgroup by attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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