How to get the selected Table cell value in datatable - asp.net-mvc

I am using jquery-2.0.3.min.js, bootstrap.min.js, jquery-ui-1.10.3.min.js, DataTables-1.9.4 with tabletools, datatables.net/blog/Twitter_Bootstrap_2
My View
<div id="windowDepartment" title="Departments"></div>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered table-hover table-condensed" id="DepartmentTable">
<thead>
<tr>
<th>departmentID</th>
<th>departmentName</th>
<th>description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Datatable initialisation Script
$(document).ready(function () {
oDepartmentTable = $('#DepartmentTable').dataTable(
{
"sDom": "T<'clear'>lfrtip",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "Department/AjaxList",
"aaSorting": [[2, 'asc'], [3, 'asc']],
"aoColumns": [
{ "mDataProp": "departmentID", "sType": "string", "bVisible": false, "bSearchable": false },
{ "mDataProp": "departmentName", "sType": "string", "bVisible": true, "bSearchable": true },
{ "mDataProp": "description", "sType": "string", "bVisible": true, "bSearchable": true },
{ "mDataProp": null,"bSearchable": false,
"sDefaultContent": '<div class="btn-group"><a class="btn btn-mini dropdown-toggle" data-toggle="dropdown" href="#"><span class="icon-circle-arrow-down"></span></a><ul class="dropdown-menu"><li><a class="editDepartment"> <i class="icon-pencil"></i> Edit</a></li><li><a class="deleteDepartment"> <i class="icon-trash"></i> Delete</a></li></ul></div>'
}
],
"oTableTools": {
"sSwfPath": "/Content/DataTables-1.9.4/extras/TableTools/media/swf/copy_csv_xls_pdf.swf"
}
});
});
EDIT FORM SCRIPT
$(document).ready(function () {
$('#DepartmentTable tbody').on('click', 'a.editDepartment', function (e) {
e.preventDefault();
//1. Dose not work shows "not available"
var aData = oDepartmentTable.fnGetData(this)
//2. Gets the correct ID if "bVisilble=true"
var departmentid = $(this).parent().parent().parent().parent().parent().children()[0].innerHTML ;
//goto Edit Controller. DepartmentID is required here
$.get('Department/Edit/' + departmentid , function (data) {
$('div#windowDepartment').html(data);
//Open Dialog box
$("#windowDepartment").dialog().dialog({
resizable: true,
height: 500,
width: 500,
modal: true,
buttons:
{
Edit: function () {
editDepartment(); //Saves the data. Works fine
}, // end ok button
Cancel: function () {
$(this).dialog("close");
}
}, //end buttons
close: function () {
$(this).dialog("close");
}
}); //end modal edit
});
});
});
My Problem. (in EDIT FORM SCRIPT)
I need the DepartmentID to pass to my controller ('Department/Edit/' + departmentid)
My observations
1) var aData = oDepartmentTable.fnGetData(this) always shows "not available" in chrome console.
2) var departmentid = $(this).parent().parent().parent().parent().parent().children()[0].innerHTML gets the correct departmentID if i use "bVisible": true in datatable initialisation.
(3) I dont want to show departmentID to the end user. if i make "bVisible": false in datatable initialisation then
var departmentid = $(this).parent().parent().parent().parent().parent().children()[0].innerHTML returns the departmentName
Thanks

Look at the discussion in the datatables forum here and fnGetPosition
Try this clickhandler instead :
$(document).ready(function () {
$('#DepartmentTable tbody tr').on('click', function (e) {
// get the position of the current data from the node
var aPos = oDepartmentTable.fnGetPosition( this );
// get the data array
var aData = oDepartmentTable.fnGetData( aPos[0] );
// get departmentID for the row
var departmentID = aData[aPos].departmentID;
console.log(departmentID);
// ... do your stuff here, eg
//goto Edit Controller. DepartmentID is required here
//$.get('Department/Edit/' + departmentid , function (data) {
//..
//..
});
});
It works for me. However, not quite as the docs says. Also, I first tried out with datatables 1.9.1 - it didnt work at all. Guess this area of datatables have had some bugs and have been refactored over the versions.

Related

checkBox filter table when field is null

I have a table with orders, one of the columns is "Tracking number"
Added a checkbox to so user can choose when to see all orders or just orders without tracking numbers.
here is the checkbox in view :
<div id="TrackingNumber">
<input type="checkbox" name="pos" value=true/>Show All
</div>
the javascript called is :
<script>
$(document).ready(function () {
$.fn.dataTable.ext.search.push(
function (settings, searchData, index, rowData, counter) {
var positions = $('input:checkbox[name="pos"]:checked').map(function () {
return this.value;
}).get();
if (positions.length === 0) {
return true;
}
if (positions.indexOf(searchData[1]) !== -1) {
return true;
}
return false;
}
)
var table = $('#tblData').DataTable();
$('input:checkbox').on('change', function () {
table.draw();
});
});</script>
when checkbox is checked it shows 0 records and when unchecked it shows all.
i want it to show all records when checkbox is checked and show only records WITHOUT tracking numbers
when Unchecked,
Help will be much appreciated :)
Here is a demo:
View:
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
<div>
<input type="checkbox" id="pos" checked="checked"/>Show All
</div>
<thead class="thead-dark">
<tr class="table-info">
<th>pal</th>
<th>via</th>
<th>con</th>
<th>TrackingNumber</th>
</tr>
</thead>
</table>
#section scripts{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(function () {
var url = "GetAllPakingList";
LoadPack(url);
})
function LoadPack(url) {
$('#tblList').DataTable({
destroy: true,
ajax: {
url: url,
},
columns: [
{ "data": "pal", responsivePriority: 1, "searchable": true },
{ "data": "via", responsivePriority: 2, "searchable": true },
{ "data": "con", responsivePriority: 3, "searchable": true },
{ "data": "trackingNumber", responsivePriority: 4, "searchable": true },
],
});
};
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var trackingNumber = data[3];
if ($('#pos').prop("checked") != true && trackingNumber!="") {
return false;
} else {
return true;
}
}
);
$('input:checkbox').on('change', function () {
var table = $('#tblList').DataTable();
table.draw();
});
</script>
}
ListOutput:
public class ListOutput
{
public string pal { get; set; }
public string via { get; set; }
public string con { get; set; }
public string TrackingNumber { get; set; }
}
result:

Reload Datatable with parameter to ajax call

Good day all, I have a project that lists rows of a specific 'node'. Each node has the ability to have a parent of that node. Think simple Hierarchy pattern.
Well. What I want to happen is, on single click of the row, i want it to be highlighted, but on double click of a row, i want the table to refresh but with the new data. The data will be based off of who has a parent of this id.
<div class="table table-striped table-bordered">
View Parent
<input id="parentID" name="ParentID" value="" type="hidden">
<table id="myDatatable">
<thead>
<tr>
<th>NodeID</th>
<th>Name</th>
<th>Desc</th>
<th>Active</th>
</tr>
</thead>
</table>
</div>
<script src="~/lib/DataTables-1.10.16/js/jquery.dataTables.js"></script>
<script src="~/lib/DataTables-1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Node/GetNodes?pParentID=' + $('#parentID').val(),
"type": "get",
"datatype": "json"
},
"autoWidth": true,
"columns": [
{
"data": "NodeID",
"render": function (pID) {
return '<input id="NodeID" value="'+pID+'" disabled/>';
}
},
{ "data": "Name", "width": "100%" },
{ "data": "Desc", "width": "100%" },
{
"data": "IsActive", "width": "50px",
'searchable': false,
"render": function (pActive) {
var status = pActive ? 'checked="checked"' : "";
return '<input class="CheckBox" disabled type="checkbox" ' + status + '" />';
}
}
]
});
$('#myDatatable tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
$('#parentID').val($('td #NodeID', this).val());
}
});
$('#myDatatable tbody').on('dblclick', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$('#parentID').val($('td #NodeID', this).val());
oTable.ajax.reload(); // DOESN"T DO WHAT I EXPECT
}
});
$("#parentIDLink").click(function () {
oTable.ajax.reload();
});
});
</script>
Above is the html for that page. Below is the MVC code that gets called to draw the list. Essentially grab all node if the id is null but grab nodes that have a specific parent if the value is not null
public ActionResult GetNodes(string pParentID)
{
if (pParentID == null || pParentID == "null" || pParentID == string.Empty)
return base.Json(new { data = m_Context.Nodes.ToList() },
new JsonSerializerSettings());
else
return base.Json(new { data = m_Context.Nodes.Where(m => m.NodeID == pParentID).ToList() },
new JsonSerializerSettings());;
}
Am i going about this the wrong way?
Create a function that relodes your data according to your selection. Inside double click event handler, call that function
function LoadDataTable() {
$.ajax({
type: "POST",
url: "/Node/GetNodes",
data: { pParentID: $('#parentID').val() },
success: function(result){
oTable.clear().draw();
oTable.rows.add(result).draw();
}
});
}
$('#myDatatable tbody').on('dblclick', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$('#parentID').val($('td #NodeID', this).val());
LoadDataTable();
}
});

Knockoutjs Custom bindig with jQueryUI Dialog

I'm trying to make a custom binding based on this code, http://jsfiddle.net/rniemeyer/WpnTU/ , Mine after a field checkbox is selected then open a jQueryUI dialog. Here is the code: http://jsfiddle.net/superjohn_2006/UFEg6/ , another question is it posible to acomplish this without a template.
<table>
<tbody data-bind="foreach: records">
<tr data-bind="foreach: fields">
<th align="left">
<input type="checkbox" data-bind="checked: chkedValue" /><span data-bind=" text: field"></span>
</th>
</tr>
<tr data-bind="foreach: fields">
<th align="left"><a data-bind="click: $root.addFormatting" href="#">Add Formatting</a></th>
</tr>
<tr data-bind="foreach: row">
<td data-bind="text: value"></td>
</tr>
</tbody>
</table>
<div id="details" data-bind="jqDialog: { autoOpen: false, resizable: false, modal: true }, template: { name: 'editTmpl', data: selectedField }, openDialog: selectedField">
</div>
<script id="editTmpl" type="text/html">
<p>
<label>Selected Field: </label>
<span data-bind="value: field" />
</p>
<button data-bind="jqButton: {}, click: $root.accept">Accept</button>
<button data-bind="jqButton: {}, click: $root.cancel">Cancel</button>
</script>
**The model
// custom binding
ko.bindingHandlers.jqDialog = {
init: function(element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {}; // initialize a jQuery UI dialog
$(element).dialog(options);
// handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).dialog("destroy");
});
}
};
//custom binding handler that opens/closes the dialog
ko.bindingHandlers.openDialog = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$(element).dialog("open");
} else {
$(element).dialog("close");
}
}
};
//custom binding to initialize a jQuery UI button
ko.bindingHandlers.jqButton = {
init: function(element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
//handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).button("destroy");
});
$(element).button(options);
}
};
var resultsData = [
{ fields: [{ field: "Field1", chkedValue: false }, { field: "Field2", chkedValue: false }] },
{ row: [{ value: "1" }, { value: "True" }] },
{ row: [{ value: "2" }, { value: "False" }] }
];
var TableModel = function (records) {
var self = this;
self.records = ko.observableArray(ko.utils.arrayMap(records, function (record) {
return { fields: ko.observableArray(record.fields), row: ko.observableArray(record.row) };
}));
self.selectedField = ko.observable();
self.addFormatting = function (formatToAdd) {
self.selectedField();
};
};
this.accept = function() {
},
this.cancel = function() {
}
ko.applyBindings(new TableModel(resultsData));
the following couple of lines need to be changed.
span data-bind="value: field"
for:
span data-bind="text: $data.field"
and,
self.selectedField();
for:
self.selectedField(formatToAdd);
modified code is in the same jsFiddle, jus add: /1/
to the end of the url address.

Ajax displays div dialog in mvc view

Pretty new to ajax.
So I have this div:
<div id="authentication" title="Authentication" >
<b>Please Generate a new token to continue!</b>
<br /><br />
<table>
<tr>
<td>Token:</td>
<td><input type="text" id="txtToken"/></td>
</tr>
<tr>
<td></td>
<td><label id="lblError"></label></td>
</tr>
</table>
</div>
which is not being displayed on my mvc view because it is a being used as a dialogue box by Ajax code below:
$('#authentication').dialog({
autoOpen: true,
width:500,
resizable: false,
beforeclose : function() { return false; },
title: 'Authentication',
modal: true,
buttons: {
"Cancel": function () {
window.location.replace("#Url.Action("Index", "Home")");
},
"Submit": function () {
var token=$('#txtToken').val();
var dlg = $(this);
$.ajax({
type: 'POST',
data: { 'token': token},
dataType: 'json',
url: '#Url.Action("CheckNewToken", "Account")',
success: function (result) {
if(result==true)
{
window.parent.jQuery('#authentication').dialog('destroy');
}
else{
$('#lblError').html("Incorrect credentials. Please try again");
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
}
});
However when the codes goes to success and result == result, the dialog box is destroyed but the div (dialog box) is then being displayed on my view which I don't want. What am I doing wrong?
Close the dialog and then destroy. This will hide the dialog completely and then destroy its dialog features. if you just do .dialog('destroy') it will just remove the dialog functionality completely and display the element as is on the page but it wont hide.
success: function (result) {
if(result==true)
{
$('#authentication').dialog('close').dialog('destroy');
}
else{
$('#lblError').html("Incorrect credentials. Please try again");
}
},
Another thing is beforeclose : function() { return false; }, you are returning false which will prevent the close event from happening. it should be beforeClose though you can remove it safely.
if the above doesnt work another option to remove the div is by subscribing to close event:-
$('#authentication').dialog({
autoOpen: true,
width:500,
resizable: false,
title: 'Authentication',
modal: true,
close:function(){
$(this).dialog('destroy').hide();
},
buttons: {
"Cancel": function () {
},
"Submit": function () {
var token=$('#txtToken').val();
var dlg = $(this);
$('#authentication').dialog('close');
}
}
});

jQuery ui dialog removes div

I have a table and within the first <td> is a hidden <div>. I want to show the div using a jQuery ui dialog which I have the following code
example tr
<tr>
<td>
<div id="subscriberNote" style="display: none;">
long message text........
</div>
long mess...
</td>
<td>
<a id="notedetails" href="#">View note</a>
</td>
</tr>
jQuery
function subscriberNotes_onload() {
$("#subscriber_notes tr").bind("click", function() {
openDialog(this);
});
}
function openDialog(row){
$(row).closest("tr").find("td:eq(0)").find("#subscriberNote").dialog({
title: "Message",
modal: true,
width: 600,
height: 530,
buttons: {
"OK": function () { $(this).dialog("close"); }
}
}).show();
}
After the dialog is shown and closed it is removing the hidden div and so has nothing to show until the page is refreshed.
Make the last function like:
function openDialog(row){
$(row).closest("tr").find("td:eq(0)").find("#subscriberNote").dialog({
title: "Message",
modal: true,
width: 600,
height: 530,
buttons: {
"OK": function () { $(this).dialog("close"); }
},
close: function(){ $(this).dialog("destroy")}
}).show();
}
According to the docs it should revert to its original state.

Resources