In my page I use jstree
and select2
. I would like to have both plug-ins integrated. Is there any way? My code looks very simple, because it relies only on the fields of integration of plug-ins and it looks like:
var dataSelect = [
{
id: 1,
text: "test"
},
{
id: 2,
text: "test2"
},
{
id: 3, text: "test3"
}
];
var dataTree = [
{
id: 1, text: "test"
},
{
id: 3,
text: "test3"
}
];
$('#jstree').jstree({
'core': {
'data': dataTree,
"themes": {
"icons": false
}
},
"checkbox": {
"keep_selected_style": false,
"three_state": true
},
"plugins": ["checkbox", "state"]
});
$("#selectSample").select2({
data: dataSelect,
multiple: true
});
As you can see, data in both cases have similar a ID. If I click test
in my tree, then I would want my select
set to "test"
. Is there any solution for this problem?
EDIT
@Nikolay Ermakov answer led me to correct thinking, but the problem is when I load my select
by ajax. When I click some option in my jstree, the data is destroyed and I cannot choose anything later in my select
. In addition, none of the options is selected on select2
.
EDIT2
When I click some option in jstree
, all options are removed, and to select
goes one blank value, which can be selected.
I guess I made your interaction two-way. Please check this fiddle: JS Fiddle.
I used changed
event of jsTree and select/unselect
events of select2.
Here is how the code looks like:
var dataSelect = [{id: "1", text: "test"},{id:"2", text: "test2"},{id:"3", text: "test3"}];
var dataTree = [{id: "1", text: "test"},{id:"3", text: "test3"}];
$("#selectSample").select2({data:dataSelect, multiple: true});
$('#jstree')
.on('changed.jstree', function (event, data) {
var $select = $("#selectSample").select2(),
selectedOptions = $select.val() || [],
optionId = data.node.id;
if( data.action == 'select_node'){
selectedOptions.push( optionId );
$select.val(selectedOptions).trigger("change");
}
if( data.action == 'deselect_node'){
selectedOptions.splice( selectedOptions.indexOf( optionId ), 1 );
$select.val(selectedOptions).trigger("change");
}
})
.jstree({
'core': {
'data': dataTree,
"themes":{
"icons":false
}
},
"checkbox": {
"keep_selected_style": false,
"three_state": true
},
"plugins" : [ "checkbox" ]
});
$("#selectSample")
.on('select2:select', function(event) {
$('#jstree').jstree('select_node', '#'+event.params.data.id, true);
})
.on('select2:unselect', function(event) {
$('#jstree').jstree('deselect_node', '#'+event.params.data.id, true);
});