ContextMenu Items in jQuery - javascript

I want to show conditional contextMenu Items via jQuery.
For Example :
I have cars in my account. And I wanted to show options on conditions.
If car is of my own then all menu items should be visible to me. And if it is shared with me then only View Menu should to visible to me.
if (type == 'vehicle') {
(function () {
var vehicle_id = node.data.vehicle_id;
var vehicle_status = '';
$.ajax({
url: baseUrl + '/check-vehicle-status/'+vehicle_id,
success: function(data) {
console.log(data);
if(data == 'shared'){
//what should I write here? to show only View option
}
}
});
items = {
"View": {
"label": "View Vehicle",
"action": function action() {
self.viewVehicle(vehicle_id);
}
},
"modify": {
"label": "Edit Vehicle",
"action": function action() {
self.editVehicle(vehicle_id);
}
},
"delete": {
"label": "Delete Vehicle",
"action": function action() {
dialogHandler.showDeleteVehicle(function () {
self.removeVehicle(vehicle_id);
});
}
},

You will have to check the data param in the context menu method like below (provided that the node.data of a tree node will have a value).
Check demo - Fiddle Demo
...
contextmenu: {
items: function (node) {
// remove default context menu items
var tmp = $.jstree.defaults.contextmenu.items();
delete tmp.rename;
delete tmp.remove;
delete tmp.ccp;
delete tmp.create;
for (menuItem in items) {
if( menuItem === 'View' || node.data !== 'shared') {
tmp[ menuItem ] = {
id: menuItem,
label: items[menuItem].label,
action: items[menuItem].action
}
}
}
return tmp;
}
},

Related

How to get selected checkbox based on first selected dropdown after refresh the page?

I have dropdown, checkboxes and button submit. First, the user will choose at dropdown (position of work). Second, the user will select the checkbox and after that submit the data. Here, after refresh it should be appear back the previous selected dropdown and checkbox. But, I did not get it. Anyone here have more better solution?
JavaScript Dropdown
//dropdown position
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "../DesignationProgramTemplate/getData.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: onChange
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
Checkbox treeview (Kendo UI)
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot,
dataType: "json"
}
},
schema: {
model: {
id : "ehorsProgramID",
hasChildren: false,
children : "items"
}
},
filter: { field: "module", operator: "startswith", value: "Accounting" }
});
$("#AccountingTree").kendoTreeView({
check: onCheck,
checkboxes: { checkChildren: true } ,
// select: onSelect,
dataSource: homogeneous,
dataBound: function(){
this.expand('.k-item');
},
dataTextField: ["module","groupname","ehorsProgramName"]
});
AJAX for submit button
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/getTemplate.php",
type: "post",
data: {'id':test,'progid':array},
success: function () {
// you will get response from your php page (what you echo or print)
kendo.alert('Success'); // alert notification
//refresh
//location.reload("http://hq-global.winx.ehors.com:9280/ehors/HumanResource/EmployeeManagement/DesignationProgramTemplate/template.php");
},
});
});
JavaScript for check checkboxes
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].id);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
var array = [];
function onCheck() {
var checkedNodes = [],treeView = $("#AccountingTree").data("kendoTreeView"),message;
var checkedNodes2 = [],treeView2 = $("#AdminSystemTree").data("kendoTreeView"),message;
var checkedNodes3 = [],treeView3 = $("#FnBTree").data("kendoTreeView"),message;
var checkedNodes4 = [],treeView4 = $("#HumanResourceTree").data("kendoTreeView"),message;
var checkedNodes5 = [],treeView5 = $("#InventoryManagementTree").data("kendoTreeView"),message;
var checkedNodes6 = [],treeView6 = $("#SalesMarketingTree").data("kendoTreeView"),message;
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
checkedNodeIds(treeView2.dataSource.view(), checkedNodes);
checkedNodeIds(treeView3.dataSource.view(), checkedNodes);
checkedNodeIds(treeView4.dataSource.view(), checkedNodes);
checkedNodeIds(treeView5.dataSource.view(), checkedNodes);
checkedNodeIds(treeView6.dataSource.view(), checkedNodes);
if (checkedNodes.length > 0) {
message = checkedNodes.filter(x => !!x).join(",");
array = checkedNodes.filter(x => !!x);
} else {
message = "No nodes checked.";
}
}
Output
JavaScript for accessing the dataItem
// cookies
var values = ["LA1","LA6","LA12"]; //array nnti array ni la localstorage/cookies
var setTreeViewValues = function(values) {
var tv = $("#AccountingTree").data("kendoTreeView");
document.write(JSON.stringify(tv));
tv.forEach(function(dataItem) {
alert("test");
if (dataItem.hasChildren) {
var childItems = dataItem.children.data();
//document.write(JSON.stringify(childItems[0].items[0].programID));
}
// document.write(JSON.stringify(dataItem.items));
if (values.indexOf(childItems[0].items[0].programID) > -1) {
dataItem.set("checked", true);
}
});
};
setTreeViewValues(values);
console.log(datasource.data()[0].hasChildren);
// end cookies
So without knowing how you are binding the existing values to the page I am assuming you will be calling the page state somewhere within your Page loading.
So I have prepared a dojo that shows two different ways of setting the checked state of the items.
https://dojo.telerik.com/EhaMIDAt/8
1. Setting at the DataSource Level
So when setting up the datasource you can add an extra attribute to your collection called checked this will then set the checked value for the item or children items when loaded. using the example I have in the dojo:
{
id: 9,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
id: 10,
text: "February.pdf",
spriteCssClass: "pdf"
},
{
id: 11,
text: "March.pdf",
spriteCssClass: "pdf",
checked: true
},
{
id: 12,
text: "April.pdf",
spriteCssClass: "pdf"
}
]
}
this will set the checked state to true for you and show the checkbox as checked.
2. Manually Set the values after loading all the DataSources.
So I have done this on a button click but this could easily be done on a ready state or some other trigger if needed. Here the button when clicked will find the node in the tree with the text Research.pdf and either set it in a checked or unchecked state for you.
$('#checked').bind('click', () => {
var box = $("#treeview").data("kendoTreeView").findByText('Research.pdf').find('input[type="checkbox"]');
box.prop('checked', !box.is(':checked'));
});
Again the sample it taken from dojo link above. Hopefully this gives you a start on getting the values set according to your specific requirements.
I would probably have the value checked state set when you load the datasource for the treeview.

While uncheck the checkbox needs to reload the search item

I'm having the search column with checkbox along with folder names. when I click the checkbox of corresponding folder, it will show their items. As well as when I click on multiple checkbox it will show their corresponding items. But when I uncheck the folder, the corresponding items doesn't remove. So I need the hard reload or refresh when I check or uncheck the checkbox or need to clear the cache for every check or uncheck.
Here is my Code:
Checkbox: Core.component.Checkbox.extend({
click: function () {
var ret=null;
var nav = this.get("controller").get('selectedNavigator');
ret = this._super.apply(this, arguments);
var states=null;
Ember.run.schedule('sync', this, function () {
Ember.run.schedule('render', this, function () {
states = this.get('parentView.itemStates');
var values = Object.keys(states).filter(function (key) {
if(states[key]){
return states[key];}
else{return;}
});
if (values.length === 0) {
Core.Action('core:contentHome', {});
} else {
this.set('parentView.model.values',values);
nav.publish();
}
});
});
return ret;
}
}),
For the Publish:
publish: function () {
var currentResultSet = this.get('resultSet'),
ctl = this.get('controller'),
form = ctl.get('formModel'),
resultSet,
data = form.sleep(2000);
if (Object.keys(data).length === 0) {
Core.view.Menu.create({
anchor: $('*[data-class-name="Core.Tab.Content.Controller.NavigationRefresh"]'),
model: [
Core.model.Menu.Item.create({
label: "Please select something to search.",
icon: 'dialog_warning'
})
]
}).show();
return;
}
resultSet = form.send();
ctl.set('loadState', 'loading');
ctl.set('resultSet', Core.model.BlankResultSet.create({
loadState: 'loading',
tabContext: Ember.get(form, 'resultSet.tabContext')
}));
resultSet.fail(function (err) {
ctl.set('loadState', 'loaded');
console.log(currentResultSet);
ctl.set('resultSet', currentResultSet);
}).always(function () {
ctl.set('loadState', 'loaded');
});
},

Datatables select first row after first load and reload

I'm using datatables and I have to select the first row of table.
The problem is select the first row when the table are reload (the table show the rooms of a building, so user can change the building).
This is my code:
function showRoom(idBuilding){
document.getElementById("roomTable").removeAttribute("style");
if ( ! $.fn.DataTable.isDataTable( '#roomTable' ) ) {
roomTable = $('#roomTable').DataTable({
responsive:true,
select: true,
"autoWidth": false,
"language": {
"emptyTable": "No room available!"
},
"ajax":{
"url": "/buildings/"+ idBuilding + "/rooms/",
"data": function ( d ) {
d.idRoomType = idRoomType;
},
"dataSrc": function ( json ) {
if (typeof json.success == 'undefined')
window.location.href = "/500";
else if (json.success){
return json.result.data;
}else{
notifyMessage(json.result, 'error');
return "";
}
},
"error": function (xhr, error, thrown) {
window.location.href = "/500";
}
},
"columns": [
{ "data": "name" },
{ "data": "capacity"},
{data:null, render: function ( data, type, row ) {
var string ="";
for (index = 0; index < data.accessories.length; ++index){
string = string + '<i aria-hidden="true" class="'+ data.accessories[index].icon+'" data-toggle="tooltip" title="'+data.accessories[index].name+'"style="margin-right:7px;" ></i>';
}
return string;
}
},
],
"fnInitComplete": function(oSettings, json) {
if (roomTable.rows().any()){
roomTable.row(':eq(0)').select();
selectedRoom(0);
}
initializeCalendar();
}
});
}
else {
roomTable.ajax.url("/buildings/"+ idBuilding + "/rooms/?idRoomType=" + idRoomType).load(selectFirstRow());
}
roomTable.off('select')
.on( 'select', function ( e, dt, type, indexes ) {
selectedRoom(indexes);
} );
roomTable.off('deselect').on( 'deselect', function ( e, dt, type, indexes ) {
reservationForm.room = -1;
$('#calendar').fullCalendar('option', 'selectable', false);
$("#calendar").fullCalendar("refetchEvents");
} );
}
function selectFirstRow(){
if (roomTable.rows().any()){
roomTable.row(':eq(0)').select();
selectedRoom(0);
}
initializeCalendar();
}
function selectedRoom(index){
var room = roomTable.rows( index ).data().toArray()[0];
reservationForm.room = room.idRoom;
$('#calendar').fullCalendar('option', 'minTime', room.startTime);
$('#calendar').fullCalendar('option', 'maxTime', room.endTime);
$('#calendar').fullCalendar('option', 'selectable', true);
$("#calendar").fullCalendar("refetchEvents");
}
On the first load all work fine, but when
roomTable.ajax.url("/buildings/"+ idBuilding + "/rooms/?idRoomType=" + idRoomType).load(selectFirstRow());
is called it seems to select the row before reload the table, so I have no row select (keep select the row of first load but now it is not visible).
Do you have idea how can I select on the load after?
UPDATE: the temporary solution is to use destroy: true but I would like a better solution like this:
if ( ! $.fn.DataTable.isDataTable( '#roomTable' ) ) {
roomTable = $('#roomTable').DataTable({
destroy: true, //it is useful because with standard code I have problem with first row selection, now it create the table each time
responsive:true,
select: true,
"autoWidth": false,
"language": {
"emptyTable": "No room available!"
},
"ajax":{
"url": "/buildings/"+ building.idBuilding + "/rooms/",
"data": function ( d ) {
d.idRoomType = idRoomType;
},
"dataSrc": function ( json ) {
if (typeof json.success == 'undefined')
window.location.href = "/500";
else if (json.success){
return json.result.data;
}else{
notifyMessage(json.result, 'error');
return "";
}
},
"error": function (xhr, error, thrown) {
window.location.href = "/500";
}
},
"fnDrawCallback": function(oSettings) {
if (roomTable.rows().any()){
roomTable.row(':eq(0)').select();
selectedRoom(0);
}
},
"fnInitComplete": function() {
initializeCalendar();
},
"columns": [
{ "data": "name" },
{ "data": "capacity"},
{data:null, render: function ( data, type, row ) {
var string ="";
for (index = 0; index < data.accessories.length; ++index){
string = string + '<i aria-hidden="true" class="'+ data.accessories[index].icon+'" data-toggle="tooltip" title="'+data.accessories[index].name+'"style="margin-right:7px;" ></i>';
}
return string;
}
},
],
});
}
else {
roomTable.ajax.url("/buildings/"+ idBuilding + "/rooms/?idRoomType=" + idRoomType).load(selectFirstRow());
}
But fnDrawCallback is called before ajax so I don't have the value, datatables keep on loading...
The fnInitComplete callback is called only when the datatable is initialized, so only once. You can use the fnDrawCallback, which is called every time the datatables redraws itself.
Just change fnInitComplete to fnDrawCallback. More about datatable callbacks (legacy version) here.

Dynamic Context Menus using JQuery

Creating Dynamic Context Menu
Here is Html Code for context menu
<div class="simple-context-menu">Right Click Me</div>
And the Javascript file is shown below
// setup:
// Install JQuery Plugin from here:
// https://github.com/swisnl/jQuery-contextMenu
// DOCS: http://swisnl.github.io/jQuery-contextMenu/
var menu1_item_names = ['item1', 'item2', 'item3'];
var menu2_item_names = ['item4', 'item5', 'item6'];
$.contextMenu({
selector: '.test-context-menu',
build: function($trigger, e) {
var options = {
callback: function(key, options) {
alert("Clicked on " + key + " on element " + options.$trigger.attr("id"));
// TODO:
// Display NAME of the menu item clicked(example: item1)
//alert("Clicked on item: " + JSON.stringify(options.items));
return false;
},
// start with an empty map
items: {
"fold1": {
"name": "menu 1",
"items": {}
},
"fold2": {}
}
};
$.each(menu1_item_names, function(k, v) {
options.items.fold1.items[k] = {
name: v
};
});
if (typeof menu2_item_names !== 'undefined' && menu2_item_names.length > 0) {
options.items.fold2 = {
"name": "menu 2",
"items": {}
}
$.each(menu2_item_names, function(k, v) {
options.items.fold2.items[k] = {
name: v
};
});
}
options.items.sep1 = "---------";
options.items.quit = {
name: "Quit"
};
return options;
}
});
Note:
When you run it and right click in the above text field a Context Menu appears
Click on any menu item, you will see(the alert box), the menu item index position eg. 0, 1 2...
Instead of the name of the item clicked in
I would like to see the name of the menu item
And the JSFiddle for the context menu.
Thanks in Advance
You can use this on the callback function :
options.$selected.text()

ng-hide & ng-show in AngularJS

Using AngularJS I want to show and hide the data related with particular id in the toggle way.
My JSON Data format is like:
$scope.things = [{
id: 1,
data: 'One',
shown: true
}, {
id: 2,
data: 'Two',
shown: false
}, {
id: 3,
data: 'Three',
shown: true
}, ];
What I want is when click on id-1 It will show text One and Hide the others, when click on id-2 will show text Two and hide others and so on.
Here is the fiddle what I tried : jsfiddle : Demo Link
i updated your code
$scope.flipMode = function (id) {
$scope.things.forEach(function (thing) {
if(id == thing.id){
thing.shown = true;
}
else{
thing.shown = false;
}
})
};
{{thing.id}}
here is the working fiddle
It should work
$scope.flipMode = function (id) {
$scope.things.forEach(function (thing) {
if(thing.id === id) {
thing.shown = true;
return;
}
thing.shown = false;
})
};
<div ng-repeat="thing in things">
{{thing.id}}
</div>
Forked working solution: http://jsfiddle.net/nypmmkrh/
Change your scope function:
$scope.flipMode = function (id) {
$scope.things.forEach(function(thing) {
if(thing.id == id) {
thing.shown = true;
} else {
thing.shown = false;
}
});
};
And pass the id in the view:
{{thing.id}}

Categories

Resources