Datatables select first row after first load and reload - javascript

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.

Related

How to select row in datatable (jquery datatables)

I'm using below code 1 to populate my datatable. However, when I tried to access my datatable using code 2, I dont get this response: alert( customerTable.row( this ).data() );
What am I doing wrong here?
Code 1
$(searchClientBtn).on("click", function () {
var clientLastName = $(clientLastNameTxt).val();
var clientFirstName = $(clientFirstNameTxt).val();
var clientMiddleName = $(clientMiddleNameTxt).val();
var clientDateOfBirth = $(clientDateOfBirthTxt).val();
if ( clientLastName.length == 0 && clientFirstName.length == 0 && clientMiddleName.length == 0 ) {
alert("Please enter search parameter/s to proceed.");
}
else {
var formData = new FormData();
formData.append("firstName", $("#clientFirstNameTxt").val());
formData.append("middleName", $("#clientMiddleNameTxt").val());
formData.append("lastName", $("#clientLastNameTxt").val());
formData.append("dateOfBirth", $("#clientDateOfBirthTxt").val());
//console.log(formData);
var booking = new booking();
booking.getListCustomer(formData, {
onSuccess: function (xdata) {
var customerTable = $("#customerTable").DataTable({
data: xdata.result,
processing: true,
columns: [
{ 'data': 'FirstName' },
{ 'data': 'MiddleName' },
{ 'data': 'LastName' },
{ 'data': 'Birthdate' }
]
});
},
onError: function (xdata) {
alert("An error occured");
}
});
$(clientSearchModal).modal("show");
}
});
Code 2
$("#customerTable").on("click", "tbody tr", function () {
alert("imclicked");
alert( customerTable.row( this ).data() );
});
Need to define variable.
$("#customerTable").on("click", "tbody tr", function () {
var customerTable = $('#customerTable').DataTable(); //Here need to define variable
alert("imclicked");
alert( customerTable.row( this ).data() );
});

Adding mask in jqGrid colum on editing line

I need to create a phone mask for some columns when I add or edit a record using jqGrid (my jqGrid version is 4.5.4).
Below my code:
this.montarGRID = function (p_gridName, p_dados, p_header, p_descriptor, p_contentName, p_primaryKey, p_filtroGrid) {
jQuery("#" + p_gridName).jqGrid( {
data : p_dados,
datatype : "local",
sortable : true,
colNames : p_header,
colModel : p_descriptor,
...
This grid is generated dynamically. I pass a json with the content of colModel.
[
{"formatter":"integer","index":"id","hidden":true,"sortable":true,"sorttype":"integer","width":75,"align":"center","name":"id"},
{"formatter":"telefone","index":"TELCONTATO01","search":true,"hidden":false,"sorttype":"text","sortable":true,"width":0,"align":"right","name":"TELCONTATO01","editoptions":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editrules":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editable":true},
{"formatter":"telefone","index":"TELCONTATO02","search":true,"hidden":false,"sorttype":"text","sortable":true,"width":0,"align":"right","name":"TELCONTATO02","editoptions":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editrules":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editable":true}
]
the method that generates the phone mask ...
(function($) {
'use strict';
$.extend($.fn.fmatter, {
mostra_telefone : function (elem) {
$(elem).mask("(99)9999-9999?");
}
});
})(jQuery);
But it is never invoked when I select, change or add the record.
Here is a pice of code which do the desired behavior. For this purpose we use inputpask plugin.
$("#jqGrid").jqGrid({
...
colModel :[
{
name: 'Telephone',
width: 100,
formatter: function(cellvalue, options, rowObject) {
var re = new RegExp("([0-9]{3})([0-9]{3})([0-9]{4,6})", "g");
return cellvalue.replace(re, "($1) $2-$3");
},
unformat : function(cellvalue, options, rowObject) {
return cellvalue.replace("(",'').replace(") ",'').replace("-",'');
},
editable: true,
edittype: "custom",
editoptions :{
custom_element : function(value, options) {
var el = document.createElement("input");
el.type="text";
el.value = value;
$(el).addClass('inline-edit-cell ui-widget-content ui-corner-all').inputmask({"mask": "(999) 999-9999"});
return el;
},
custom_value : function(elem, operation, value) {
if(operation === 'get') {
return $(elem).val().replace("(",'').replace(") ",'').replace("-",'').replace(/\_/g,'');;
} else if(operation === 'set') {
$(elem).val(value);
}
}
},
editrules : {
requiered : true,
custom : true,
custom_func : function(val, name) {
// special replace mask at end
var cel = val.replace("(",'').replace(") ",'').replace("-",'').replace(/\_/g,'');
if(cel.length !== 10) {
return [false,"Please, enter correct phone number"];
}
return [true,""];
}
}
},
....
],
....
});
This code should work in you version too.
Also here is a link to the demo.
I solved the problem with this:
function custom_element_telefone(value, options){
var el = document.createElement("input");
el.type="text";
el.value = value;
$(el).addClass('inline-edit-cell ui-widget-content ui-corner-all').inputmask({"mask": "(99)9999-9999#"});
return el;
};
this.montarGRID = function (p_gridName, p_dados, p_header, p_descriptor, p_contentName, p_primaryKey, p_filtroGrid) {
p_descriptor.forEach(col => {
if (!col.editoptions) return;
if (!col.editoptions.custom_element) return;
switch (col.editoptions.custom_element) {
case "custom_element_telefone":
col.editoptions.custom_element = custom_element_telefone;
break;
}
});
jQuery("#" + p_gridName).jqGrid( {
data : p_dados,
datatype : "local",
sortable : true,
colNames : p_header,
colModel : p_descriptor,
...

Select2 group with Infinite scroll

I am using select2 group option with infinite scroll and data are coming by Ajax calling per page 10. Here is some problem arises, suppose user 1 has 15 data and user 2 has 15 data, at first 10 data are coming from user 1 and in next page 10 (5 data for user1 and 5 data for user2). no problem for data getting but the problem is user 1 group showing double. How can I prevent double display to my select2 options group? Has there any way to make an option group again?
HTML CODE
<div class="container">
<form id="frm">
<h1>Solution 1</h1>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="tagInput">Get data by ajax calling</label>
<select class="form-control" id="pictures_tag_input">
</select>
<small class="form-text text-muted"><p class="text-info">Infinite Scroll</p></small>
</div>
</div>
</div>
</form>
</div>
JS CODE
$(document).ready(function() {
// solution 1
//example.com/articles?page[number]=3&page[size]=1
http: $("#pictures_tag_input").select2({
placeholder: "Search for options",
ajax: {
url: "https://jsonplaceholder.typicode.com/users/1/todos",
dataType: "json",
global: false,
cache: true,
delay: 250,
minimumInputLength: 2,
data: function(params) {
// console.log(params.page || 1);
return {
q: params.term, // search term
_page: params.page || 1,
_limit: 10 // page size
};
},
processResults: function(data, params) {
params.page = params.page || 1;
var datx = getNestedChildren(data);
// console.log(datx);
return {
results: datx,
pagination: {
more: true
}
};
} //end of process results
} // end of ajax
});
function getNestedChildren(list) {
var roots = [];
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (roots.length === 0) {
var obj = {
text: "User " + node.userId,
children: [{ id: node.id, text: node.title }]
};
roots.push(obj);
} else {
var obj = {
text: "User " + node.userId,
children: [{ id: node.id, text: node.title }]
};
var rootArray = $.map(roots, function(val, i) {
var vl = "User " + node.userId;
if (val.text === vl) return val;
else return undefined;
});
if (rootArray.length > 0) {
var obj1 = {
id: node.id,
text: node.title
};
rootArray[0].children.push(obj1);
} else {
roots.push(obj);
}
}
}
return roots;
}
});
Demo
https://codepen.io/mdshohelrana/pen/MLVZEG
Just try to use the following code
templateResult: function(data) {
if (typeof data.children != 'undefined') {
$(".select2-results__group").each(function() {
if (data.text == $(this).text()) {
return data.text = '';
}
});
}
return data.text;
}
NOTE: Need to group from server side, Other wise you have to make master details from client side.
the accepted answer didn't work for me and I don't see why should that work. A return in the $.each will not return from the templateResult() function.
Here is an approach that worked for me.
It is not necessary to build a nested list by getNestedChildren(list) on javascript side. It is much easier to build it on server side instead.
The appearance of search results in the dropdown (options and the optgroups) can be customized by using the templateResult option. I removed the duplicated optgroups and labels by this option.
check the templateResult: formatOptions, part of the code
$(document).ready(function() {
$("#pictures_tag_input").select2({
placeholder: "Search for options",
templateResult: formatOptions,
ajax: {
url: "https://jsonplaceholder.typicode.com/users/1/todos",
dataType: "json",
global: false,
cache: true,
delay: 250,
minimumInputLength: 2,
data: function(params) {
return {
q: params.term,
_page: params.page || 1,
_limit: 10
};
},
processResults: function(data, params) {
params.page = params.page || 1;
return {
results: data,
pagination: {
more: true
}
};
} //end of process results
} // end of ajax
});
function formatOptions(item, container, $el) {
// optgroups section
if (item.children && item.children.length > 0) {
// don't format the repeated optgroups!
if ($(".select2-results__group").text() === item.text) {
return;
}
if ($('[aria-label="' + item.text + '"]').length > 0) {
return;
}
// the first occasion of the given optgroup
return $el;
}
// options section
// here you can implement your own logic
// if you want to customise the output of the options
$el.addClass('something-special-result result');
return $el;
}
});
maybe the problem is a source of a data
You call user 1 .... server return a 1
You call user 2 .... server return a 1
You call user 3 .... server return a 2
You call user 4 .... server return a 2
You call user 5 .... server return a 3
You call user 6 .... server return a 3
curent_user = 1;
$(document).ready(function() {
http: $("#pictures_tag_input").select2({
placeholder: "Search for options",
ajax: {
url: "https://jsonplaceholder.typicode.com/users/1/todos",
dataType: "json",
global: false,
cache: false,
minimumInputLength: 2,
data: function(params) {
console.log("params",params || 1);
return {
q: params.term, // search term
_page: curent_user,
_limit: 10 // page size
};
},
processResults: function(data, params) {
curent_user += 2;
var datx = getNestedChildren(data);
console.log("data: ", data);
return {
results: datx,
pagination: {
more: true
}
};
} //end of process results
} // end of ajax
});
function getNestedChildren(list) {
var roots = [];
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (roots.length === 0) {
var obj = {
text: "User " + node.userId,
children: [{ id: node.id, text: node.title }]
};
roots.push(obj);
} else {
var obj = {
text: "User " + node.userId,
children: [{ id: node.id, text: node.title }]
};
var rootArray = $.map(roots, function(val, i) {
var vl = "User " + node.userId;
if (val.text === vl) return val;
else return undefined;
});
if (rootArray.length > 0) {
var obj1 = {
id: node.id,
text: node.title
};
rootArray[0].children.push(obj1);
} else {
roots.push(obj);
}
}
}
return roots;
}
});
so if you skip a one step
You call user 1 .... server return a 1
You call user 3 .... server return a 2
You call user 5 .... server return a 3
I just found a better solution which does not result in a (duplicated) optgroup being rendered as an empty option:
processResults: function( json, params ){
setTimeout( function() {
var $prevOptions = false;
var $prevGroup = false;
// loop
$('.select2-results__option[role="group"]').each(function(){
// vars
var $options = $(this).children('ul');
var $group = $(this).children('strong');
// compare to previous
if( $prevGroup && $prevGroup.text() === $group.text() ) {
$prevOptions.append( $options.children() );
$(this).remove();
return;
}
// update vars
$prevOptions = $options;
$prevGroup = $group;
});
}, 1 );
return json;
}
Advanced Custom Fields uses the exact same code for their WordPress plugin in order to fix this issue, ajax-load and group posts from different post-types.

getting main class object inside function without using arrow function

In my angular project, I am using datatable where I have row grouping and row callbacks.
datatable options
openPositionDatatableOptions = {
sDom: 'rt<"bottom"p>',
ajax: (data, callback, settings) => {
this.service.getOpenPositions()
.map(data => data.json().data).catch(this.handleError)
.subscribe(jsondata => {
this.openPositionsData = jsondata;
jsondata.forEach(element => {
if (element.side === 'SLD') {
element.openQuantity = '-' + element.openQuantity;
}
element['delta'] = 0;
element['pl'] = 0;
});
if (jsondata) {
callback({
aaData: jsondata
});
}
},
error => {
this.notifiicationAlert('Some Error Occured While Retrieving Positions Data', 'WARNING');
});
},
columns: [
{ data: 'account.brokerId' },
{ data: 'contract.localSymbol' },
{ data: 'openQuantity' },
{ data: 'delta' },
{ data: 'pl' },
{
data: null,
orderable: false,
defaultContent:
'<a class="fa fa-remove" style="color:#8B0000"></a>',
responsivePriority: 2
}
],
//Grouping By Row Logic
"columnDefs": [
{ "visible": false, "targets": 0 }
],
"order": [[0, 'asc']],
"drawCallback": function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(0, { page: 'current' }).data().each(function(group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="5"><div class="row"><div class="col-lg-6" style="text-align:left">' + group + '</div><div class="col-lg-6" style="text-align:right"><button class="datatableGroupingBtn btn btn-default btn-xs fa fa-remove" value='+group+'></button></div></div></td></tr>'
);
last = group;
}
});
// jQuery button click event
$(".datatableGroupingBtn").on('click',(value)=>{
var clickedRow = value.currentTarget.value;
});
},
//Grouping By Row Logic Ends
rowCallback: (row: Node, data: any | Object, index: number) => {
$('a', row).bind('click', () => {
this.service.closePosition(data.id).catch(this.handleError).subscribe(
res => {
if (res.status == 200) {
//TODO Re-implement this using web-socket
if ($.fn.DataTable.isDataTable(this.service.openPositionTableAlias)) {
const table = $(this.service.openPositionTableAlias).DataTable();
if (this.openPositionsData.length > 1) {
$('td', row)
.parents('tr')
.remove();
} else {
table.clear().draw();
}
this.notifiicationAlert('Position Closed Successfully', 'SUCCESS');
}
}
},
(error: Response) => {
this.notifiicationAlert('Some Problem While Closing The Position', 'WARNING');
}
);
});
return row;
}
};
In my datatable options, I have a drawCallback function inside I am grouping the rows. Inside the function, I also have a jquery click event over #datatableGroupingBtn
"drawCallback": function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(0, { page: 'current' }).data().each(function(group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="5"><div class="row"><div class="col-lg-6" style="text-align:left">' + group + '</div><div class="col-lg-6" style="text-align:right"><button class="datatableGroupingBtn btn btn-default btn-xs fa fa-remove" value='+group+'></button></div></div></td></tr>'
);
last = group;
}
});
// jQuery button click event
$(".datatableGroupingBtn").on('click',(value)=>{
var clickedRow = value.currentTarget.value;
});
}
Now my requirement is, I have to access the class level this that is My OrderComponent class object inside the jquery click event binding of #datatableGroupingBtn. I know that this can be done if I use arrow function over the drawCallback but if I use then other required functionalities won't work as you can see that I have used some properties using function() level this inside drawCallback function.
My component
import { NotificationService } from './../shared/utils/notification.service';
import { Global } from 'app/shared/global';
import { endponitConfig } from 'environments/endpoints';
import { Observable } from 'rxjs';
import { Http } from '#angular/http';
import { OrderService } from './order.service';
import { Component, OnInit, OnDestroy, AfterViewInit } from '#angular/core';
import { Router } from '#angular/router';
declare var $: any;
#Component({
selector: 'app-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.css']
})
export class OrderComponent {
openPositionsData: any;
openOrdersData: any;
openPositionDatatableOptions = {
sDom: 'rt<"bottom"p>',
ajax: (data, callback, settings) => {
this.service.getOpenPositions()
.map(data => data.json().data).catch(this.handleError)
.subscribe(jsondata => {
this.openPositionsData = jsondata;
jsondata.forEach(element => {
if (element.side === 'SLD') {
element.openQuantity = '-' + element.openQuantity;
}
element['delta'] = 0;
element['pl'] = 0;
});
if (jsondata) {
callback({
aaData: jsondata
});
}
},
error => {
this.notifiicationAlert('Some Error Occured While Retrieving Positions Data', 'WARNING');
});
},
columns: [
{ data: 'account.brokerId' },
{ data: 'contract.localSymbol' },
{ data: 'openQuantity' },
{ data: 'delta' },
{ data: 'pl' },
{
data: null,
orderable: false,
defaultContent:
'<a class="fa fa-remove" style="color:#8B0000"></a>',
responsivePriority: 2
}
],
//Grouping By Row Logic
"columnDefs": [
{ "visible": false, "targets": 0 }
],
"order": [[0, 'asc']],
"drawCallback": function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(0, { page: 'current' }).data().each(function(group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="5"><div class="row"><div class="col-lg-6" style="text-align:left">' + group + '</div><div class="col-lg-6" style="text-align:right"><button class="datatableGroupingBtn btn btn-default btn-xs fa fa-remove" value='+group+'></button></div></div></td></tr>'
);
last = group;
}
});
// jQuery button click event
$(".datatableGroupingBtn").on('click',(value)=>{
var clickedRow = value.currentTarget.value;
});
},
//Grouping By Row Logic Ends
rowCallback: (row: Node, data: any | Object, index: number) => {
$('a', row).bind('click', () => {
this.service.closePosition(data.id).catch(this.handleError).subscribe(
res => {
if (res.status == 200) {
//TODO Re-implement this using web-socket
if ($.fn.DataTable.isDataTable(this.service.openPositionTableAlias)) {
const table = $(this.service.openPositionTableAlias).DataTable();
if (this.openPositionsData.length > 1) {
$('td', row)
.parents('tr')
.remove();
} else {
table.clear().draw();
}
this.notifiicationAlert('Position Closed Successfully', 'SUCCESS');
}
}
},
(error: Response) => {
this.notifiicationAlert('Some Problem While Closing The Position', 'WARNING');
}
);
});
return row;
}
};
constructor(private http : Http, private service : OrderService){
this.http.get(Global.serviceUrl).subscribe(response=>{
this.openPositionsData = response.json().data;
})
}
}
Assign your openPositionDatatableOptions in the constructor, after declaring a self variable
openPositionDatatableOptions : any;
constructor()
{
const self = this;
this.openPositionDatatableOptions = {
//....
"drawCallback": function (settings) {
//....
// jQuery button click event
$(".datatableGroupingBtn").on('click',(value)=>{
var clickedRow = value.currentTarget.value;
console.log(self);//<=== self is your class instance
});
},
}
Inside the method your jQuery event binding is, declare a variable like so
let self = this;
now you should be able to use this variable in your jquery click event binding

ContextMenu Items in jQuery

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;
}
},

Categories

Resources