├── LICENSE ├── README.md ├── example ├── 1.png ├── 2.png ├── 3.png └── example.html └── src ├── select2totree.css └── select2totree.js /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 clivezhg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

This project is not maintained by the author.

2 |
3 | 4 | Select2-to-Tree 5 | ======= 6 | 7 | Select2-to-Tree is an extension to Select2, a popular select boxes library: https://github.com/select2/select2. 8 | 9 | Though Select2 is very versatile, it only supports a single level of nesting. See https://select2.github.io/options.html#how-many-levels-of-nesting-are-allowed: 10 |
11 | Because Select2 falls back to an <optgroup> when creating nested options, only a single level of nesting is supported. Any additional levels of nesting is not guarenteed to be displayed properly across all browsers and devices.
12 | 13 | Select2-to-Tree extends Select2 to support arbitrary level of nesting. 14 | 15 | Select2 compatibility 16 | --------------------- 17 | * Select2 4+ 18 | 19 | Browser compatibility 20 | --------------------- 21 | * IE 8+ 22 | * Chrome 8+ 23 | * Firefox 10+ 24 | * Safari 3+ 25 | * Opera 10.6+ 26 | 27 | Usage 28 | ----- 29 | Firstly, you need to know the usage of Select2: https://github.com/select2/select2 30 | 31 | Then, in your HTML document, you add the Select2 library (the `*.js` file & `*.css` file, currently the version should be 4.0+), and the Select2-to-Tree library (the `*.js` file & `*.css` file in the "`src`" folder). jQuery is also needed. 32 | 33 | There are 2 ways to use Select2-to-Tree: 34 | 35 |

1. Use data, and empty <select> element(see "Example 1" in "example/example.html"):

36 | 37 | Suppose your HTML is like this: 38 | ```html 39 | 41 | ``` 42 | And your data: 43 | ```js 44 | var mydata = [ 45 | {id:1, text:"USA", inc:[ 46 | {text:"west", inc:[ 47 | {id:111, text:"California", inc:[ 48 | {id:1111, text:"Los Angeles", inc:[ 49 | {id:11111, text:"Hollywood"} 50 | ]}, 51 | {id:1112, text:"San Diego", selected:"true"} 52 | ]}, 53 | {id:112, text:"Oregon"} 54 | ]} 55 | ]}, 56 | {id:2, text:"India"}, 57 | {id:3, text:"中国"} 58 | ]; 59 | ``` 60 | And you call Select2-to-Tree like the following: 61 | ```js 62 | $("#sel_1").select2ToTree({treeData: {dataArr:mydata}, maximumSelectionLength: 3}); 63 | ``` 64 | "`{treeData: {dataArr:mydata}`" is for Select2-to-Tree, "`maximumSelectionLength: 3`" is for Select2 (and you can set the other Select2 arguments if needed) 65 | 66 | About the data structure: "`id`" will be used as option value, "`text`" will be used as option label, and "`inc`" will be used to specify sub-level options. If your data structure is not like this, you can set arguments in "`treeData`" to change the default behavior, e.g., `treeData: {dataArr: mydata, valFld: "value", labelFld: "name", incFld: "sub"}`: 67 | - `dataArr`, an array containing the data. 68 | - `valFld`, the option value field, it's "`id`" by default. (if the value is empty, the corresponding option will be unselectable, see the "west" option in the example) 69 | - `selFld`, the selected value field, it's "`selected`" by default. 70 | - `labelFld`, the option label field, it's "`text`" by default. 71 | - `incFld`, the sub options field, it's "`inc`" by default. 72 | - `dftVal`, the default value. 73 | 74 | For `valFld` and `labelFld`, you can give a object path (eg: `item.label`. see "Example 4" in "example/example.html"). 75 | 76 | The above are all the parameters supported by Select2-to-Tree. 77 | 78 |

2. directly create the <select> element(see "Example 2" in "example/example.html"):

79 | 80 | If it's hard to create the required data structure, you can directly create the <select> element. It's like the following: 81 | ```html 82 | 90 | ``` 91 | - the classes `l1`,`l2`,`l3`,`l4`,`l5`..., setting the nesting level. 92 | - the attribute `data-pup`, setting the value of the parent level option. 93 | - the class `non-leaf`, setting whether the option has children or not. 94 | 95 | Then, you call Select2-to-Tree (the "`treeData`" argument of Select-to-Tree is not needed here, but you can set arguments for Select2): 96 | ```js 97 | $("#sel_2").select2ToTree(); 98 | ``` 99 | 100 | Styling 101 | ----- 102 | Select-to-Tree uses CSS rules(in the select2totree.css file) to control the indent & size of each level, e.g.: 103 | ``` 104 | .s2-to-tree .select2-results__option.l8 { 105 | margin-left: 6.0em; 106 | font-size: 0.75em; 107 | } 108 | ``` 109 | By default, Select-to-Tree defines 8 levels, if you need more than 8 levels, you can add your own CSS rules. 110 | You can also change or override the pre-defined CSS rules to match your requirements. 111 | 112 | Constraints 113 | ----------- 114 | - AJAX data source is not supported. 115 | - It is a little slower than plain Select2, because there are extra operations to do. Anyway, according to my test (you can check "Example 3" in "example/example.html", click the "India -> north"), 1500 options is basically acceptable, which is enough in most of the real world cases. 116 | 117 | Illustration 118 | ------------ 119 | See "Example 3" in "example/example.html": 120 | 121 | 122 | 123 | Copyright and license 124 | --------------------- 125 | The license is available within the repository in the [LICENSE][license] file. 126 | -------------------------------------------------------------------------------- /example/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clivezhg/select2-to-tree/7514110fd3d8bc055450ec1609f4c7b5490c55e2/example/1.png -------------------------------------------------------------------------------- /example/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clivezhg/select2-to-tree/7514110fd3d8bc055450ec1609f4c7b5490c55e2/example/2.png -------------------------------------------------------------------------------- /example/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clivezhg/select2-to-tree/7514110fd3d8bc055450ec1609f4c7b5490c55e2/example/3.png -------------------------------------------------------------------------------- /example/example.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Select2-to-Tree * example 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Example 1

14 | 16 | 34 | 35 |
36 | 37 |

Example 2

38 | 46 | 49 | 50 |
51 | 52 |

Example 3

53 | 55 | 74 | 75 |
76 | 77 |

Example 4

78 | 80 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /src/select2totree.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Select2-to-Tree CSS 1.1.1 3 | * https://github.com/clivezhg/select2-to-tree 4 | */ 5 | .s2-to-tree * { 6 | box-sizing: border-box; 7 | } 8 | 9 | .s2-to-tree .select2-results__option.l1 { 10 | margin-left: 0.6em; 11 | font-size: 1em; 12 | } 13 | .s2-to-tree .select2-results__option.l2 { 14 | margin-left: 1.4em; 15 | font-size: 0.95em; 16 | } 17 | .s2-to-tree .select2-results__option.l3 { 18 | margin-left: 2.2em; 19 | font-size: 0.91em; 20 | } 21 | .s2-to-tree .select2-results__option.l4 { 22 | margin-left: 3.0em; 23 | font-size: 0.87em; 24 | } 25 | .s2-to-tree .select2-results__option.l5 { 26 | margin-left: 3.8em; 27 | font-size: 0.83em; 28 | } 29 | .s2-to-tree .select2-results__option.l6 { 30 | margin-left: 4.5em; 31 | font-size: 0.8em; 32 | } 33 | .s2-to-tree .select2-results__option.l7 { 34 | margin-left: 5.3em; 35 | font-size: 0.77em; 36 | } 37 | .s2-to-tree .select2-results__option.l8 { 38 | margin-left: 6.0em; 39 | font-size: 0.75em; 40 | } 41 | 42 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l1 { 43 | margin-right: 0.6em; 44 | } 45 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l2 { 46 | margin-right: 1.4em; 47 | } 48 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l3 { 49 | margin-right: 2.2em; 50 | } 51 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l4 { 52 | margin-right: 3.0em; 53 | } 54 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l5 { 55 | margin-right: 3.8em; 56 | } 57 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l6 { 58 | margin-right: 4.5em; 59 | } 60 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l7 { 61 | margin-right: 5.3em; 62 | } 63 | .s2-to-tree .select2-dropdown[dir*="rtl"] .select2-results__option.l8 { 64 | margin-right: 6.0em; 65 | } 66 | 67 | .s2-to-tree li.select2-results__option.non-leaf .expand-collapse:hover { 68 | color: red; 69 | cursor: pointer; 70 | } 71 | .s2-to-tree li.select2-results__option.non-leaf .expand-collapse:before { /* no :: in IE8 */ 72 | content: "+"; 73 | position: absolute; 74 | left: -0.35em; 75 | top: 0.1em; 76 | font-size: larger; 77 | } 78 | .s2-to-tree .select2-dropdown[dir*="rtl"] li.select2-results__option.non-leaf .expand-collapse:before { 79 | right: -0.35em; 80 | } 81 | .s2-to-tree li.select2-results__option.non-leaf.opened .expand-collapse:before { 82 | content: "−"; 83 | } 84 | 85 | .s2-to-tree .select2-results__option[aria-disabled="true"] .expand-collapse { 86 | color: black; 87 | } 88 | 89 | .s2-to-tree .item-label { 90 | display: inline-block; 91 | margin-left: 0.5em; 92 | padding: 3px; 93 | width: calc(100% - 11px); /* IE8 will fit the content */ 94 | } 95 | .s2-to-tree .select2-dropdown[dir*="rtl"] .item-label { 96 | margin-right: 0.5em; 97 | } 98 | 99 | .s2-to-tree li.select2-results__option { 100 | position: relative; 101 | padding: 0px; 102 | height: auto; 103 | overflow-y: hidden; 104 | } 105 | 106 | .s2-to-tree li.select2-results__option[data-pup] { 107 | display: none; 108 | } 109 | .s2-to-tree li.select2-results__option[data-pup].showme { 110 | display: block; 111 | overflow-y: visible; 112 | } 113 | 114 | .s2-to-tree.select2-container .select2-results__option--highlighted[aria-selected] > span.item-label { 115 | background-color: #5897fb; 116 | color: white; 117 | } 118 | .s2-to-tree.select2-container li.select2-results__option[aria-selected="true"] > span.item-label { 119 | background-color: #ddd; 120 | } 121 | 122 | .s2-to-tree.select2-container li.select2-results__option--highlighted[aria-selected], 123 | .s2-to-tree.select2-container li.select2-results__option[aria-selected="true"] { 124 | background-color: inherit; 125 | color: inherit; 126 | } 127 | 128 | .s2-to-tree li.select2-results__option.l1 { 129 | display: block; 130 | overflow-y: visible; 131 | } 132 | 133 | .s2-to-tree.searching-result li.select2-results__option { 134 | height: auto; 135 | display: block; 136 | } 137 | -------------------------------------------------------------------------------- /src/select2totree.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Select2-to-Tree 1.1.1 3 | * https://github.com/clivezhg/select2-to-tree 4 | */ 5 | (function ($) { 6 | $.fn.select2ToTree = function (options) { 7 | var opts = $.extend({}, options); 8 | 9 | if (opts.treeData) { 10 | buildSelect(opts.treeData, this); 11 | } 12 | 13 | opts._templateResult = opts.templateResult; 14 | opts.templateResult = function (data, container) { 15 | var label = data.text; 16 | if (typeof opts._templateResult === "function") { 17 | label = opts._templateResult(data, container); 18 | } 19 | var $iteme = $("").append(label); 20 | if (data.element) { 21 | var ele = data.element; 22 | container.setAttribute("data-val", ele.value); 23 | if (ele.className) container.className += " " + ele.className; 24 | if (ele.getAttribute("data-pup")) { 25 | container.setAttribute("data-pup", ele.getAttribute("data-pup")); 26 | } 27 | if ($(container).hasClass("non-leaf")) { 28 | return $.merge($(''), $iteme); 29 | } 30 | } 31 | return $iteme; 32 | }; 33 | 34 | window.expColMouseupHandler = function (evt) { 35 | toggleSubOptions(evt.target || evt.srcElement); 36 | /* prevent Select2 from doing "select2:selecting","select2:unselecting","select2:closing" */ 37 | evt.stopPropagation ? evt.stopPropagation() : evt.cancelBubble = true; 38 | evt.preventDefault ? evt.preventDefault() : evt.returnValue = false; 39 | } 40 | 41 | var s2inst = this.select2(opts); 42 | 43 | s2inst.on("select2:open", function (evt) { 44 | var s2data = s2inst.data("select2"); 45 | s2data.$dropdown.addClass("s2-to-tree"); 46 | s2data.$dropdown.removeClass("searching-result"); 47 | var $allsch = s2data.$dropdown.find(".select2-search__field").add( s2data.$container.find(".select2-search__field") ); 48 | $allsch.off("input", inputHandler); 49 | $allsch.on("input", inputHandler); 50 | }); 51 | 52 | /* Show search result options even if they are collapsed */ 53 | function inputHandler(evt) { 54 | var s2data = s2inst.data("select2"); 55 | if ($(this).val().trim().length > 0) { 56 | s2data.$dropdown.addClass("searching-result"); 57 | } 58 | else { 59 | s2data.$dropdown.removeClass("searching-result"); 60 | } 61 | } 62 | 63 | return s2inst; 64 | }; 65 | 66 | /* Build the Select Option elements */ 67 | function buildSelect(treeData, $el) { 68 | 69 | /* Support the object path (eg: `item.label`) for 'valFld' & 'labelFld' */ 70 | function readPath(object, path) { 71 | var currentPosition = object; 72 | for (var j = 0; j < path.length; j++) { 73 | var currentPath = path[j]; 74 | if (currentPosition[currentPath]) { 75 | currentPosition = currentPosition[currentPath]; 76 | continue; 77 | } 78 | return 'MISSING'; 79 | } 80 | return currentPosition; 81 | } 82 | 83 | function buildOptions(dataArr, curLevel, pup) { 84 | var labelPath; 85 | if (treeData.labelFld && treeData.labelFld.split('.').length> 1){ 86 | labelPath = treeData.labelFld.split('.'); 87 | } 88 | var idPath; 89 | if (treeData.valFld && treeData.valFld.split('.').length > 1) { 90 | idPath = treeData.valFld.split('.'); 91 | } 92 | 93 | for (var i = 0; i < dataArr.length; i++) { 94 | var data = dataArr[i] || {}; 95 | var $opt = $(""); 96 | if (labelPath) { 97 | $opt.text(readPath(data, labelPath)); 98 | } else { 99 | $opt.text(data[treeData.labelFld || "text"]); 100 | } 101 | if (idPath) { 102 | $opt.val(readPath(data, idPath)); 103 | } else { 104 | $opt.val(data[treeData.valFld || "id"]); 105 | } 106 | if (data[treeData.selFld || "selected"] && String(data[treeData.selFld || "selected"]) === "true") { 107 | $opt.prop("selected", data[treeData.selFld || "selected"]); 108 | } 109 | if($opt.val() === "") { 110 | $opt.prop("disabled", true); 111 | $opt.val(getUniqueValue()); 112 | } 113 | $opt.addClass("l" + curLevel); 114 | if (pup) $opt.attr("data-pup", pup); 115 | $el.append($opt); 116 | var inc = data[treeData.incFld || "inc"]; 117 | if (inc && inc.length > 0) { 118 | $opt.addClass("non-leaf"); 119 | buildOptions(inc, curLevel+1, $opt.val()); 120 | } 121 | } // end 'for' 122 | } // end 'buildOptions' 123 | 124 | buildOptions(treeData.dataArr, 1, ""); 125 | if (treeData.dftVal) $el.val(treeData.dftVal); 126 | } 127 | 128 | var uniqueIdx = 1; 129 | function getUniqueValue() { 130 | return "autoUniqueVal_" + uniqueIdx++; 131 | } 132 | 133 | function toggleSubOptions(target) { 134 | $(target.parentNode).toggleClass("opened"); 135 | showHideSub(target.parentNode); 136 | } 137 | 138 | function showHideSub(ele) { 139 | var curEle = ele; 140 | var $options = $(ele).parent(".select2-results__options"); 141 | var shouldShow = true; 142 | do { 143 | var pup = ($(curEle).attr("data-pup") || "").replace(/'/g, "\\'"); 144 | curEle = null; 145 | if (pup) { 146 | var pupEle = $options.find(".select2-results__option[data-val='" + pup + "']"); 147 | if (pupEle.length > 0) { 148 | if (!pupEle.eq(0).hasClass("opened")) { // hide current node if any parent node is collapsed 149 | $(ele).removeClass("showme"); 150 | shouldShow = false; 151 | break; 152 | } 153 | curEle = pupEle[0]; 154 | } 155 | } 156 | } while (curEle); 157 | if (shouldShow) $(ele).addClass("showme"); 158 | 159 | var val = ($(ele).attr("data-val") || "").replace(/'/g, "\\'"); 160 | $options.find(".select2-results__option[data-pup='" + val + "']").each(function () { 161 | showHideSub(this); 162 | }); 163 | } 164 | })(jQuery); 165 | --------------------------------------------------------------------------------