can jsTree use radio check - javascript

i know there is a plugin for jsTree named jquery.tree.checkbox.js.
that make the tree node multi checkable.
i just wondered if there is a plugin to raido check the tree node?
or how can i modify jquery.tree.checkbox.js to achieve that?

This can simply be done by adding the attribute
rules:{
multiple : false
}
Inside the configuration of the tree.
This will make it impossible to choose multiple entries.

#Asaf's answer seems to no longer work on version 3.3.1 in 2016. You now need to set multiple on core:
$jstree.jstree({
core: {
multiple: false,
...
}
});

Setting multiple:false will still allow cascading so you need to turn that off too.
version 3.3.3
$(".tree").jstree({
plugins: ["checkbox"],
core: {
data: ...,
multiple: false
},
checkbox: {
three_state: false,
cascade: "none"
}
});

The radio button option is still not released, so you have to change the chceckbox option as single select.
bind('check_node.jstree', function(e, data) {
var currentNode = data.rslt.obj.attr("id");
$("#tree").jstree("get_checked",null,true).each
(function () {
if(currentNode != this.id){
jQuery.jstree._reference($("#tree")).uncheck_node('#'+this.id);
}
});
});
refer this http://jsfiddle.net/bwTrP/1/

Using jsTree version 3.2.1 with the checkbox plugin it is possible to emulate radiobutton behaviour handling the 'changed' event as follows:
//jstree configuration:
'checkbox': {
three_state: false, //required for the cascade none to work
cascade: 'none' //no auto all_children<->parent selection
},
//...
var resetting = false;
$('#tree').on('changed.jstree', function (e, data) {
if (resetting) //ignoring the changed event
{
resetting = false;
return;
}
if ($("#multiselect").is(':checked') == false && data.selected.length > 1) {
resetting = true; //ignore next changed event
data.instance.uncheck_all(); //will invoke the changed event once
data.instance.check_node(data.node/*currently selected node*/);
}
});
JSFiddle: JSTree radiobutton behaviour example using checkbox plugin

Related

Adding auto complete to jstree input node

I am creating a JsTree which has an input box Node. I want to enable auto-complete for this input box. The application is in angular4, but the file i am using for creating the jstree is a .js file.
inst.create_node(obj, {
li_attr : {
'class' : 'child-menu listener-menu'
},
a_attr:{
'ondragover' : 'allowDropSR(event,"widgets")',
'ondrop' : 'dropSR(event,"widgets")'
},
text : "<span>Enter Country here</span>"
},
"last", function(new_node) {
new_node.data = {
file : true,
stopDrilldown : true,
hasParent : true
};
setTimeout(function () {
inst.edit(new_node);
$('.jstree-rename-input').attr();
},0);
});
$('.widget-list-tab a').tab('show');
$('.jstree-clicked').next('ul').find('li:last').find('a').focus();
},
Best approach would have been to write your own jsTree plugin. You can possibly hook the keydown event of jsTree for edit box to populate your list of items as a autocomplete suggestion and using jQuery UI autocomplete feature.
.bind("keydown.jstree", function(e) {
if(e.target.tagName && e.target.tagName.toLowerCase() === "input"
&& e.target.className.toLowerCase() === "jstree-rename-input" ) {
$(".jstree-rename-input").autocomplete({
// AJAX can be used for list here
source: countries
});
}
});
countries: is the list suggestion.
You can see in more details at https://everyething.com/jsTree-with-AutoComplete-Box

ExtJS : Re-selecting the same value does not fire the select event

Normally, when you select an item in a combobox, you would expect it to fire the select event. However, if you try to select an item that was already selected, the select event is not fired. That is the "normal" behavior of an ExtJs combobox.
I have a specific need for an ExtJS combobox: I need it to fire the select event even if I re-select the same value. But I cannot get it to work. Any help would be much appreciated!
Example here: https://fiddle.sencha.com/#view/editor&fiddle/2n11
Open the dev tools to see when the select event is fired.
I'm using ExtJS Classic 6.6.0.
Edit: I answered my own question and updated the Fiddle with working solution.
try to look at this:
ExtJS 4 Combobox event for selecting selected value
Its for earlier ExtJS version, but catching click event for itemlist may help you out too..
I found the culprit: it all happens in the SelectionModel of the combobox BoundList, in the method doSingleSelect.
So if we extend Ext.Selection.DataViewModel and Ext.form.field.ComboBox, we can force the select event to be fired every time.
Ext.define( "MyApp.selection.DataViewModelExt", {
"extend": "Ext.selection.DataViewModel",
"alias": "selection.dataviewmodelext",
"doSingleSelect": function(record, suppressEvent) {
var me = this,
changed = false,
selected = me.selected,
commit;
if (me.locked) {
return;
}
// already selected.
// should we also check beforeselect?
/*
if (me.isSelected(record)) {
return;
}
*/
commit = function() {
// Deselect previous selection.
if (selected.getCount()) {
me.suspendChanges();
var result = me.deselectDuringSelect([record], suppressEvent);
if (me.destroyed) {
return;
}
me.resumeChanges();
if (result[0]) {
// Means deselection failed, so abort
return false;
}
}
me.lastSelected = record;
if (!selected.getCount()) {
me.selectionStart = record;
}
selected.add(record);
changed = true;
};
me.onSelectChange(record, true, suppressEvent, commit);
if (changed && !me.destroyed) {
me.maybeFireSelectionChange(!suppressEvent);
}
}
});
We also must extend the combobox to force using our extended DataViewModel. The only thing to change is the onBindStore method where it instancies the DataViewModel:
Ext.define( "MyApp.form.field.ComboBoxEx", {
"extend": "Ext.form.field.ComboBox",
"alias": "widget.comboboxex",
"onBindStore": function(store, initial) {
var me = this,
picker = me.picker,
extraKeySpec,
valueCollectionConfig;
// We're being bound, not unbound...
if (store) {
// If store was created from a 2 dimensional array with generated field names 'field1' and 'field2'
if (store.autoCreated) {
me.queryMode = 'local';
me.valueField = me.displayField = 'field1';
if (!store.expanded) {
me.displayField = 'field2';
}
// displayTpl config will need regenerating with the autogenerated displayField name 'field1'
if (me.getDisplayTpl().auto) {
me.setDisplayTpl(null);
}
}
if (!Ext.isDefined(me.valueField)) {
me.valueField = me.displayField;
}
// Add a byValue index to the store so that we can efficiently look up records by the value field
// when setValue passes string value(s).
// The two indices (Ext.util.CollectionKeys) are configured unique: false, so that if duplicate keys
// are found, they are all returned by the get call.
// This is so that findByText and findByValue are able to return the *FIRST* matching value. By default,
// if unique is true, CollectionKey keeps the *last* matching value.
extraKeySpec = {
byValue: {
rootProperty: 'data',
unique: false
}
};
extraKeySpec.byValue.property = me.valueField;
store.setExtraKeys(extraKeySpec);
if (me.displayField === me.valueField) {
store.byText = store.byValue;
} else {
extraKeySpec.byText = {
rootProperty: 'data',
unique: false
};
extraKeySpec.byText.property = me.displayField;
store.setExtraKeys(extraKeySpec);
}
// We hold a collection of the values which have been selected, keyed by this field's valueField.
// This collection also functions as the selected items collection for the BoundList's selection model
valueCollectionConfig = {
rootProperty: 'data',
extraKeys: {
byInternalId: {
property: 'internalId'
},
byValue: {
property: me.valueField,
rootProperty: 'data'
}
},
// Whenever this collection is changed by anyone, whether by this field adding to it,
// or the BoundList operating, we must refresh our value.
listeners: {
beginupdate: me.onValueCollectionBeginUpdate,
endupdate: me.onValueCollectionEndUpdate,
scope: me
}
};
// This becomes our collection of selected records for the Field.
me.valueCollection = new Ext.util.Collection(valueCollectionConfig);
// This is the selection model we configure into the dropdown BoundList.
// We use the selected Collection as our value collection and the basis
// for rendering the tag list.
//me.pickerSelectionModel = new Ext.selection.DataViewModel({
me.pickerSelectionModel = new MyApp.selection.DataViewModelExt({
mode: me.multiSelect ? 'SIMPLE' : 'SINGLE',
// There are situations when a row is selected on mousedown but then the mouse is dragged to another row
// and released. In these situations, the event target for the click event won't be the row where the mouse
// was released but the boundview. The view will then determine that it should fire a container click, and
// the DataViewModel will then deselect all prior selections. Setting `deselectOnContainerClick` here will
// prevent the model from deselecting.
ordered: true,
deselectOnContainerClick: false,
enableInitialSelection: false,
pruneRemoved: false,
selected: me.valueCollection,
store: store,
listeners: {
scope: me,
lastselectedchanged: me.updateBindSelection
}
});
if (!initial) {
me.resetToDefault();
}
if (picker) {
me.pickerSelectionModel.on({
scope: me,
beforeselect: me.onBeforeSelect,
beforedeselect: me.onBeforeDeselect
});
picker.setSelectionModel(me.pickerSelectionModel);
if (picker.getStore() !== store) {
picker.bindStore(store);
}
}
}
}
});
Then just use the extended combobox in your app. By doing that, the select event will be fired every time.

How to disable drag and drop with jquery.shapeshift?

I'm using this plugin grid system with drag and drop functionality:
https://github.com/McPants/jquery.shapeshift.
You can call the shapeshift function and pass it the parameters to enable and disable the drag and drop functionality.
$(".container").shapeshift({
enableDrag: true,
});
I want to be able to turn on and off this feature. I used this code:
var dragState = 0;
$(".switch").on("click", function() {
if(dragState == 0) {
options = {
enableDrag: true,
}
dragState = 1;
} else {
options = {
enableDrag: false,
}
dragState = 0;
}
$(".container").shapeshift(options);
});
When I run this code I can turn on drag and drop but not back off again.
Does anyone have any suggestions or experience with this plugin?
Use http://mcpants.github.io/jquery.shapeshift/ as a reference.
Basicaly all you need to do is:
$(function(){
var sso = {
minColumns: 3,
enableDrag: false
};
var ss = $(".container").shapeshift(sso);
$('button').click(function () {
sso.enableDrag = true;
ss.trigger('ss-destroy');
ss.shapeshift(sso);
});
});
I simplified the example to show what needs to be done in this fiddle:
http://jsfiddle.net/carisch19/hDm4e/2/
Added enable and disable buttons:
http://jsfiddle.net/carisch19/hDm4e/4/
Sorry for answering on such an old question but i was just going through shapeshift.js and understand that for disabling drag and drop we can destroy it but not in such a long way and there is no need to take it to variable.
Hope you will interested in this short way and update your codes.
Below is the code
$('div').trigger("ss-destroy");
Above code is sufficient for destroying and also a very clean and convenient way according to me.
Try once!

Any way to prevent "select_node.jstree" from being called when node closed in the jstree?

When you open nodes, it's fine. The "select_node.jstree" is not called. However, when you select a node and then close its' parent, jstree fires "select_node.jstree" for that parent node for some strange reason. Is there any way around this or is that just a flaw with jstree? I'd appreciate the help! Here's my code:
$("#RequirementsTree")
.bind("select_node.jstree", function(event, data) {
ReqNode = data.rslt.obj;
$("#req_tree_modal").dialog({ height: 400, width: 600, modal: true, closeOnEscape: true, resizable: false, show: "blind" });
$("#RMSDoc_ParentNodeID").val(data.rslt.obj.attr("id").substring(4));
if(is_requirement_node(data))
{
dispEditRequirementView();
var ReqCheck = data.rslt.obj.attr("name");
#* This is a REQUIREMENT *#
if(ReqCheck == "requirement")
{
// Ajax call to Server with requirement id passed in
$.ajax({
type: "POST",
url: '#Url.Content("~/RMS/getRequirementStateByID")',
data: {
ReqID : data.rslt.obj.attr("id").substring(4)
},
success: function(new_data) {
if(new_data == 1){
$("#RMSDoc_ReqEnabled").attr("checked", "checked");
$("#RMSDoc_ReqEnabled").val("true");
}
else if(new_data == 0) {
$("#RMSDoc_ReqEnabled").removeAttr("checked");
$("#RMSDoc_ReqEnabled").val("false");
}
}
});
$("#RMSDoc_RBSRequirement_RequirementsId").val(data.rslt.obj.attr("id").substring(4));
$("#RMSDoc_RBSRequirement_RequirementsText").val($.trim(data.rslt.obj.text()));
$("#ExistingTreeSubmit").val("#Model.RMSDoc.RMSEditReqButton.ConfigurableLabelDesc");
}
else {
alert("Requirement node select error");
}
}
#* This is a TREE BRANCH *#
else
{
dispAddRequirementView();
$("#RMSDoc_TreeBranch_Text").val($.trim($('.jstree-clicked').text()));
$("#RMSDoc_TreeBranch_id").val(data.rslt.obj.attr("id").substring(4));
$("#RMSDoc_TreeBranch_Level").val(data.rslt.obj.attr("name").substring(7));
$("#RMSDoc_RBSRequirement_RequirementsText").val("");
$("#ExistingTreeSubmit").val("#Model.RMSDoc.RMSCreateReqButton.ConfigurableLabelDesc");
}
})
Update:
I found a way to get it to work within the plugin, add the following to the "ui" config section:
"ui": {
"select_limit": 1,
"selected_parent_close":false
},
I believe what was happening is that when a sub-node was selected, collapsing the parent node would cause the parent node to be selected, triggering the event.
---------- Original Answer ---------------------
I'm not sure on the answer working within the bounds of the plugin. But I did find a work-around.
I added a class to each of the anchor () tags inside the tree "an".
<li class='jstree-closed' id="phtml_3" rel="folder">
test node 2
</li>
Then I wired JQuery to look for anchors with this class, and handled my click that way.
instance.on("click", "a.an", function (e) {
alert("click");
});
I still need to add code to find the ID from the parent-container, not optimal... but I don't have to compete with the collapse anymore for my click.

How to implement toggle functionality on JQuery UI Selectable?

I'm using JQuery UI - Selectable. I want to deselect the element if it has been pressed and it has already been selected (toggle)
Could you help me to add this functionality please !
Because of all the class callbacks, you're not going to do much better than this:
$(function () {
$("#selectable").selectable({
selected: function (event, ui) {
if ($(ui.selected).hasClass('click-selected')) {
$(ui.selected).removeClass('ui-selected click-selected');
} else {
$(ui.selected).addClass('click-selected');
}
},
unselected: function (event, ui) {
$(ui.unselected).removeClass('click-selected');
}
});
});
You already have that functionality with jQuery UI selectable if you're holding down the Ctrl key while clicking.
If you really need that as the default functionality, you don't need to use selectable, you can do it just as a simple onclick handler, like what nolabel suggested.
Or... you might as well edit jquery.ui.selectable.js and add an option which does just what you need. Shouldn't be too hard, there are 4 places where event.metaKey is checked, make sure if your option is set, just run the codepaths as if event.metaKey was always true.
As the selectables could use some more customisation, you could also make a feature request for jQuery UI developers to include it in the next official version.
You have to inject two simple elements in the code to achieve what you want. This just inverts the metaKey boolean, whenever you need inverted/toggle functionality.
options: {
appendTo: 'body',
autoRefresh: true,
distance: 0,
filter: '*',
tolerance: 'touch',
inverted: false /* <= FIRST*/
},
_mouseStart: function(event) {
var self = this;
this.opos = [event.pageX, event.pageY];
if (this.options.disabled)
return;
var options = this.options;
if (options.inverted) /* <= SECOND*/
event.metaKey = !event.metaKey; /* <= SECOND*/

Categories