Getting DataTable row clicked on with context menu - javascript

I would like to add a context menu to each of my DataTable rows.
I want to get the row that was clicked on and then some way to identify it (I suppose the first cell value which contains the primary key would work) and then send an AJAX request containing the PK and option clicked.
I have figured out how to get the row by using "tr" as a selector, but how can I get the 1st cell's value (which contains the primary key). This prints out all of the cells:
$(function(){
$.contextMenu({
selector: 'td',
trigger: 'right',
callback: function(key, options) {
var m = $(options.$trigger).text();
window.console && console.log(m) || alert(m);
},
items: {
"delete": {name: "Delete", icon: "delete"},
});
});
Also, is this the best way to do this? I plan to have ~10 options in the context menu that interact with the rows. I am using Django as the backend.

Always use the API when you want to interact with DT. If you have an instance
var table = $('#example').DataTable( {..} )
then retrieve the current row by passing options.$trigger which holds the <tr> node :
$.contextMenu({
selector: 'tr',
trigger: 'right',
callback: function(key, options) {
var row = table.row(options.$trigger)
switch (key) {
case 'delete' :
row.remove().draw()
break;
case ...
}
},
items: {
'delete': { name: 'Delete', icon: 'delete' },
...
}
})
but how can I get the 1st cell's value (which contains the primary
key).
row.data()[0]
demo -> http://jsfiddle.net/z2q5scgr/

Related

Datatables has only 10 rows accessible outside the DataTables creation function

I am using Django and in one of my tamplates I use datatables (1.10.19) to display my table data.
This is how my code looks like:
$(document).ready( function () {
table = $('#mytable').DataTable({
"pagingType": "full_numbers",
data: dataSet,
columns: [
{ title: "Naslov zahtjeva" },
{ title: "Datum slanja" },
{ title: "Status" },
{ title: "Rok Izvršenja." },
{ title: "Id zahtjeva" },
],
"fnCreatedRow": function(row, data, index){
$(row).addClass("clickable-row");
$(row).attr('data-href', data[4]);
$(row).addClass("table_row_point");
},
});
Problem occurs at the line -> $(row).attr('data-href', data[4]);
I have a different function that is suposed to use that 'ID' from 'data-href' attribute in order to go to another page like this
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
});
Thing is it works fine for first 10 rows, and when I try 'console.log( this );' I get
Only for the first 10 rows, and it acts like other 3000 don't even exist, I believe it is connected to the default value of 10 rows that appear, but it makes no sense to me for data to be displayed normally, but the 'tr' element not to exist for all, but 10 of them.
Note: When I place this function into DataTable creation code (1st snippet) it shows all the tr elements
$('#mytable tbody').on( 'click', 'tr', function () {
console.log( this );
} );
If someone has any idea it would be much appreciated
fnCreatedRow function is executed everytime datatable creates the <tr> element in the dom. Since you have enabled pagination, function is run only on the <tr> elements created at the time. If you move on to next page, you'll see that console prints next set of rows.
By the way I think createdRow is preferred over old fnCreatedRow naming convention. https://datatables.net/reference/option/createdRow

jqGrid - checkbox editing not able to edit selected row

In my jqGrid, I have a checkbox which is also available for editing, i.e. a user can click on the checkbox and that checkbox's value will be updated in the database. That is working fine. However when I click on the checkbox and if I try clicking on it again, nothing happens. The row does not get saved. Theoretically the unchecked value of the checkbox should be saved. But this does not happen.
I have tried referring to this answer of Oleg but it does not help.
The weird problem is if I select another row and then try to unselect the checkbox again, I do see a save request going.
I am guessing this is because I am trying to edit a row which is currently selected. But I am not sure what I am doing wrong here.
This is what I am doing in my beforeSelectRow
beforeSelectRow: function (rowid, e) {
var $target = $(e.target),
$td = $target.closest("td"),
iCol = $.jgrid.getCellIndex($td[0]),
colModel = $(this).jqGrid("getGridParam", "colModel");
if (iCol >= 0 && $target.is(":checkbox")) {
if (colModel[iCol].name == "W3LabelSelected") {
console.log(colModel[iCol].name);
$(this).setSelection(rowid, true);
$(this).jqGrid('resetSelection');
$(this).jqGrid('saveRow', rowid, {
succesfunc: function (response) {
$grid.trigger('reloadGrid');
return true;
}
});
}
}
return true;
},
Configuration:
jqGrid version: Latest free jqGrid
Data Type: Json being saved to server
Minimal Grid Code: jsFiddle
EDIT: After Oleg's answer this is what I have so far:
beforeSelectRow: function (rowid, e) {
var $self = $(this),
iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]),
cm = $self.jqGrid("getGridParam", "colModel");
if (cm[iCol].name === "W3LabelSelected") {
//console.log($(e.target).is(":checked"));
$(this).jqGrid('saveRow', rowid, {
succesfunc: function (response) {
$grid.trigger('reloadGrid');
return true;
}
});
}
return true; // allow selection
}
This is close to what I want. However if I select on the checkbox the first time and the second time, the console.log does get called everytime. However the saveRow gets called only when I check the checkbox and then click on it again to uncheck it the first time and never after that. By default the checkbox can be checked or unchecked based on data sent from server.
In the image, the request is sent after selecting the checkbox two times instead of being sent everytime.
UPDATE: As per #Oleg's suggestion, I have implemented cellattr and called a function inside. In the function I simply pass the rowid and update the checkbox of that rowid on the server.
Here's the code I used:
{
name: 'W3LabelSelected',
index: 'u.W3LabelSelected',
align: 'center',
width: '170',
editable: false,
edittype: 'checkbox',
formatter: "checkbox",
search: false,
formatoptions: {
disabled: false
},
editoptions: {
value: "1:0"
},
cellattr: function (rowId, tv, rawObject, cm, rdata) {
return ' onClick="selectThis(' + rowId + ')"';
}
},
and my selectThis function:
function selectThis(rowid) {
$.ajax({
type: 'POST',
url: myurl,
data: {
'id': rowid
},
success: function (data) {
if (data.success == 'success') {
$("#list").setGridParam({
datatype: 'json',
page: 1
}).trigger('reloadGrid');
} else {
$("<div title='Error' class = 'ui-state-error ui-corner-all'>" + data.success + "</div>").dialog({});
}
}
});
}
FIDDLE
I think there is a misunderstanding in the usage of formatter: "checkbox", formatoptions: { disabled: false }. If you creates non-disabled checkboxs in the column of the grid in the way then the user just see the checkbox, which can be clicked and which state can be changed. On the other side nothing happens if the user changes the state of the checkbox. On the contrary the initial state of the checkbox corresponds to input data of the grid, but the changed checkbox makes illusion that the state is changed, but nothing will be done automatically. Even if you use datatype: "local" nothing is happens and even local data will be changed on click. If you do need to save the changes based on the changing the state of the checkbox then you have to implement additional code. The answer demonstrates a possible implementation. You can change the state of some checkboxes on the corresponding demo, then change the page and go back to the first page. You will see that the state of the checkbox corresponds the lates changes.
Now let us we try to start inline editing (start editRow) on select the row of the grid. First of all inline editing get the values from the rows (editable columns) using unformatter, saves the old values in internal savedRow parameter and then it creates new editing controls inside of editable cells on the place of old content. Everything is relatively easy in case of using standard disabled checkbox of formatter: "checkbox". jqGrid just creates enabled checkboxs on the place of disabled checkboxs. The user can change the state of the checkboxs or the content of any other editable columns and saves the changes by usage of Enter for example. After that the selected row will be saved and will be not more editable. You can monitor the changes of the state of the checkbox additionally (by usage editoptions.dataEvents with "change" event for example) and call saveRow on changing the state. It's important that the row will be not editable after the saving. If you do need to hold the row editable you will have to call editRow once more after successful saving of the row. You can call editRow inside of aftersavefunc callback of saveRow, but I recommend you to wrap the call of editRow inside of setTimeout to be sure that processing of previous saving is finished. It's the way which I would recommend you.
On the other side if you try to combine enabled checkboxs of formatter: "checkbox" with inline editing then you will have much more complex processing. It's important that enabled checkbox can be changed first of all before processing of onclick and onchange event handlers. The order of 3 events (changing the state of the checkbox, processing of onclick and processing of onchange) can be different in different web browsers. If the method editRow be executing it uses unformatter of checkbox-formatter to get the current state of the checkbox. Based of the value of the state editRow replace the content of the cell to another content with another enabled checkbox. It can be that the state of the checkbox is already changed, but editRow interprets the changes state like the initial state of the checkbox. In the same way one can call saveRow only after editRow. So you can't just use saveRow inside of change handler of formatter: "checkbox", formatoptions: { disabled: false }, because the line is not yet in editing mode.
UPDATED: The corresponding implementation (in case of usage formatter: "checkbox", formatoptions: { disabled: false }) could be the following:
editurl: "SomeUrl",
beforeSelectRow: function (rowid, e) {
var $self = $(this),
$td = $(e.target).closest("tr.jqgrow>td"),
p = $self.jqGrid("getGridParam"),
savedRow = p.savedRow,
cm = $td.length > 0 ? p.colModel[$td[0].cellIndex] : null,
cmName = cm != null && cm.editable ? cm.name : "Quantity",
isChecked;
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
if (cm != null && cm.name === "W3LabelSelected" && $(e.target).is(":checkbox")) {
if (savedRow.length > 0) {
// some row is editing now
isChecked = $(e.target).is(":checked");
if (savedRow[0].id === rowid) {
$self.jqGrid("saveRow", rowid, {
extraparam: {
W3LabelSelected: isChecked ? "1" : "0",
},
aftersavefunc: function (response) {
$self.jqGrid("editRow", rowid, {
keys: true,
focusField: cmName
});
}
});
}
} else {
$.ajax({
type: "POST",
url: "SomeUrl", // probably just p.editurl
data: $self.jqGrid("getRowData", rowid)
});
}
}
if (rowid) {
$self.jqGrid("editRow", rowid, {
keys: true,
focusField: cmName
});
}
return true; // allow selection
}
See jsfiddle demo http://jsfiddle.net/OlegKi/HJema/190/

jQuery datatables add class to tr

I am using jQuery and datatables. I want to add a class to the TR element of a particular row. I know how to find the row. The console.dir(row); shows the row object and that starts with a tr element. I can't get the jQuery selector to do anything though. What am I missing?
table = $('#resultTable').DataTable({
aaSorting: [],
ajax: {...},
columnDefs: [...],
createdRow: function (row, data, index) {
//
// if the second column cell is blank apply special formatting
//
if (data[1] == "") {
console.dir(row);
$('tr', row).addClass('label-warning');
}
}
});
$('tr', row) is looking for a tr element in the context of row, meaning it will search for a tr element inside the row provided as context parameter.
According to API, this should work
$(row).addClass("label-warning");
You would just have to use the createdRow
$('#data-table').DataTable( {
createdRow: function( row, data, dataIndex ) {
// Set the data-status attribute, and add a class
$( row ).find('td:eq(0)')
.attr('data-status', data.status ? 'locked' : 'unlocked')
.addClass('asset-context box');
}
} );
DataTable().row.add() situation:
If you want to add class when using row add function in Datatables, you could get the TR-DOM from node() method:
var datatable = $('#resultTable').DataTable();
var trDOM = datatable.row.add( [
"Col-1",
"Col-2"
] ).draw().node();
$( trDOM ).addClass('myClass');
To set the Id attribute on the row <tr> use:
//....
rowId: "ShipmentId",
columns: [...],
//....
To set a class name on the <tr> use this calback
createdRow: function (row, data, dataIndex) {
$(row).addClass('some-class-name');
},
ref: https://datatables.net/reference/option/createdRow
To set a class on the <td> use
"columns": [
{
data:"",
className: "my_class",
render: function (data, type, row) { return "..."; }
},
{
data:"",
className: "my_class",
render: function (data, type, row) { return "..."; }
},
//...
]
Something similar for 'columnDefs'
ref: https://datatables.net/reference/option/columns.className
Also you can add class to tr by pass through json data that you send to datatable. It's enough that every json item has DT_RowClass.
For example:
{
DT_RowAttr = new
{
attr1 = "1",
attr2 = "2"
}
DT_RowClass = "majid",
DT_RowId = "rowId"
}
In this example DT_RowId value apply to id attribute of any tr tag and DT_RowAttr value apply some custom attribute to tr tag.
Another solution:
createdRow: function (row,data) {
var stsId = data.Ise_Sts_Cost_ID;
if (stsId == 3)
$(row).addClass('table-warning');
else if (stsId == 4)
$(row).addClass('table-success');
else
$(row).addClass('table-danger');
}

Pass Id to a Onclick Function JQGrid

I have a JQGrid.I need to take some Id to the OnClick function.In my scenario i wanted to get BasicId to the OnClick function.
MyCode
function grid() {
//JqGrid
$('#griddata').html('<table class="table" id="jqgrid"></table>')
$('#jqgrid').jqGrid({
url: '/Admin/GetBasicData/',
datatype: 'json',
mtype: 'GET',
//columns names
colNames: ['BasicId','Images'],
//columns model
colModel: [
{ name: 'BasicId', index: 'BasicId', resizable: false },
{
name: 'Images',
width: 120,
formatter: function () {
return "<button class='btn btn-warning btn-xs' onclick='OpenDialog()' style='margin-left:30%'>View</button>";
}
},
//Some Code here
Open Dialog Function
function OpenDialog(BasicId)
{
//Some code here
}
You can use onclick='OpenDialog.call(this, event)' instead of onclick='OpenDialog()'. You will have this inside of OpenDialog initialized to the clicked <button> and the event.target. Thus your code could be like the following
function OpenDialog (e) {
var rowid = $(this).closest("tr.jqgrow").attr("id"),
$grid = $(this).closest(".ui-jqgrid-btable"),
basicId = $grid.jqGrid("getCell", rowid, "BasicId");
// ...
e.stopPropagation();
}
One more option is even better: you don't need to specify any onclick. Instead of that you can use beforeSelectRow callback of jqGrid:
beforeSelectRow (rowid, e) {
var $td = $(e.target).closest("td"),
iCol = $.jgrid.getCellIndex($td[0]),
colModel = $(this).jqGrid("getGridParam", "colModel"),
basicId = $(this).jqGrid("getCell", rowid, "BasicId");
if (colModel[iCol].name === "Images") { // click in the column "Images"
// one can make additional test for
// if (e.target.nodeName.toUpperCase() === "button")
// to be sure that it was click to the button
// and not the click on another part of the column
OpenDialog(rowid);
return false; // don't select the row - optional
}
}
The main advantages of the last approach: one don't need to make any additional binding (every binding get memory resources and it take time). There are already exist on click handler in the grid and one can use it. It's enough to have one click handler because of event bubbling. The e.target provide us still full information about the clicked element.
Writing js event in your buttons html is not a good idea, its against 'un-obtrusive javasript' principle. You can instead add a click event on the entire grid in the render function and in the callback, filter out based on whether the button was clicked.
//not sure of the syntax of jqgrid, but roughly:
render: function(){
$('#jqgrid').unbind('click').on('click', function(){
if($(e.target).hasClass('btn-warning')){
var tr = $(e.target).parent('tr');
//retrieve the basicId from 'tr'
OpenDialog(/*pass the basicId*/)
}
})
}

How to call a function inside a Javascript class (jQuery, jSuggest)

I'm using the code found in this jsbin: http://jsbin.com/asahe5/10/edit
There is a function within that class called addItem, which adds an auto-suggested item to the page. However, there is no API built in to add something by clicking on a button for example.
I have tried the following, but it doesn't work (Uncaught TypeError: Object [object Object] has no method 'addItem'):
var test = $("#test").jSuggest({
source: 'http://example.com/page.php',
minChars: 1,
keyDelay: 200,
selectedItemProp: 'name',
seekVal: 'name',
startText: 'Enter a country',
newItem: false,
newText: 'Please select a country from the list.',
selectionAdded: function(elem, data){ add_country(data.value); },
selectionRemoved: function(elem, data){ elem.fadeTo("fast", 0, function(){ elem.remove(); rem_country(data.value); }); }
});
function add_item(object, id) {
test.addItem(object, id);
}
The most relevant part of the plugin:
(function($){
$.fn.jSuggest = function(options) {
var defaults = {
source: {}, // Object or URL where jSuggest gets the suggestions from.
uniqID: false,
startText: 'Enter a Value', // Text to display when the jSuggest input field is empty.
emptyText: 'No Results Found', // Text to display when their are no search results.
preFill: {}, // Object from which you automatically add items when the page is first loaded.
limitText: 'No More Values Are Allowed', // Text to display when the number of selections has reached it's limit.
newItem: false, // If set to false, the user will not be able to add new items by any other way than by selecting from the suggestions list.
newText: 'Adding New Values Is Not Allowed', // Text to display when the user tries to enter a new item by typing.
selectedItemProp: 'value', // Value displayed on the added item
selectProp: 'value', // Name of object property added to the hidden input.
seekVal: 'value', // Comma separated list of object property names.
queryParam: 'q', // The name of the param that will hold the search string value in the AJAX request.
queryLimit: false, // Number for 'limit' param on ajax request.
extraParams: '', // This will be added onto the end of the AJAX request URL. Make sure you add an '&' before each param.
matchCase: false, // Make the search case sensitive when set to true.
minChars: 1, // Minimum number of characters that must be entered before the search begins.
keyDelay: 400, // The delay after a keydown on the jSuggest input field and before search is started.
resultsHighlight: true, // Option to choose whether or not to highlight the matched text in each result item.
selectionLimit: false, // Limits the number of selections that are allowed.
showResultList: true, // If set to false, the Results Dropdown List will never be shown at any time.
selectionClick: function(elem){}, // Custom function that is run when a previously chosen item is clicked.
selectionAdded: function(elem, data){}, // Custom function that is run when an item is added to the items holder.
selectionRemoved: function(elem, data){ elem.remove(); }, // Custom function that is run when an item is removed from the items holder.
spotFirst: true, // Option that spots the first suggestions on the results list if true.
formatList: false, // Custom function that is run after all the data has been retrieved and before the results are put into the suggestion results list.
beforeRetrieve: function(string){ return string; }, // Custom function that is run before the AJAX request is made, or the local objected is searched.
retrieveComplete: function(data){ return data; },
resultClick: function(data){}, // Custom function that is run when a search result item is clicked.
resultsComplete: function(){} // Custom function that is run when the suggestion results dropdown list is made visible.
};
// Merge the options passed with the defaults.
var opts = $.extend(defaults, options);
// Get the data type of the source.
var dType = typeof opts.source;
.....................................
function addItem(data, num) {
// Add to the hidden input the seleced values property from the passed data.
hiddenInput.val(hiddenInput.val()+data[opts.selectProp]+',');
// If a selected item is clicked, add the selected class and call the custom selectionClick function.
var item = $('<li class="as-selection-item" id="as-selection-'+num+'"></li>').click(function() {
opts.selectionClick.call(this, $(this));
itemsHolder.children().removeClass('selected');
$(this).addClass('selected');
});
// If the close cross is clicked,
var close = $('<a class="as-close">x</a>').click(function() {
// Remove the item from the hidden input.
hiddenInput.val(hiddenInput.val().replace(data[opts.selectProp]+',',''));
// Call the custom selectionRemoved function.
opts.selectionRemoved.call(this, item, data);
input.focus();
return false;
});
// Insert the item with the selectedItemProp as text and the close cross.
orgLI.before(item.html(data[opts.selectedItemProp]).prepend(close));
// Call the custom selectionAdded function with the recently added item as elem and its associated data.
opts.selectionAdded.call(this, orgLI.prev(), data);
}
.....................................
});
}
};
})(jQuery);
You can't call that function without changing the plugin to expose the function as a visible API.

Categories

Resources