Skip to content
This repository has been archived by the owner on Jun 19, 2024. It is now read-only.

Auto Expand selected option #26

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions example/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ <h3>Example 2</h3>
<select id="sel_2" style="width:8em">
<option value="1" class="l1 non-leaf">opt_1</option>
<option value="11" data-pup="1" class="l2 non-leaf">opt_11</option>
<option value="111" data-pup="11" class="l3">opt_111</option>
<option value="111" data-pup="11" class="l3" selected="selected">opt_111</option>
<option value="12" data-pup="2" class="l2">opt_12</option>
<option value="2" class="l1">opt_2</option>
<option value="3" class="l1">opt_3</option>
</select>
<script>
$("#sel_2").select2ToTree();
$("#sel_2").select2ToTree({expandSelectedItemParents:true});
</script>

<br>
Expand Down
25 changes: 25 additions & 0 deletions src/select2totree.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
buildSelect(opts.treeData, this);
}

if (opts.expandSelectedItemParents) {
var selectionChain=updateSelectionChain(this);
}

opts._templateResult = opts.templateResult;
opts.templateResult = function (data, container) {
var label = data.text;
Expand All @@ -24,6 +28,12 @@
if (ele.getAttribute("data-pup")) {
container.setAttribute("data-pup", ele.getAttribute("data-pup"));
}
if (opts.expandSelectedItemParents && (selectionChain.indexOf(ele.value)>-1)) {
$(container).addClass("showme");
if ($(container).hasClass("non-leaf") && selectionChain.indexOf(ele.value)!==0) {
$(container).addClass("opened");
}
}
if ($(container).hasClass("non-leaf")) {
return $.merge($('<span class="expand-collapse" onmouseup="expColMouseupHandler(event);"></span>'), $iteme);
}
Expand All @@ -48,6 +58,10 @@
$allsch.off("input", inputHandler);
$allsch.on("input", inputHandler);
});

s2inst.on("select2:select", function (evt) {
selectionChain=updateSelectionChain(this);
});

/* Show search result options even if they are collapsed */
function inputHandler(evt) {
Expand Down Expand Up @@ -161,4 +175,15 @@
showHideSub(this);
});
}
function updateSelectionChain(sl2) {

var values=[];
var currElm=$(sl2).find('option[value='+$(sl2).val()+']');
do
{
values.push(currElm.val());
}
while((currElm=$(sl2).find('option[value='+currElm.data('pup')+']')).length);
return values;
}
})(jQuery);