onClick function for button inside jquery DataTable - javascript

I have a button for each row inside my jquery DataTable. I want when I click the button to alert the value of the first columns of the selected record.
The problem is that, with the code I have for the button, it does not work.
This is the documentation that I have followed: https://datatables.net/examples/ajax/null_data_source.html
Here is my code:
jQuery
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WebService1.asmx/Bind",
dataType: 'json',
success: function (data) {
$('#datatable').DataTable({
data: data,
columns: [
{ 'data': 'CenterID' },
{ 'data': 'CenterName' },
{ 'data': 'LicenseKey' },
{ 'data': 'ExpiryDate' },
{ 'data': 'YearID' },
{ 'data': 'Date' },
// This is where I add the button
{ "defaultContent": "<button>Edit</button>"}
]
});
}
});
//This is where I make an attempt to add functionality for the button in the datatable
$('#datatable tbody').on('click', 'button', function () {
var data = table.row($(this).parents('tr')).data();
alert("The value is: " + data[0]);
});
});
HTML
<table id="datatable" class="display" style="width: 100%">
<thead>
<tr>
<th>CenterID</th>
<th>CenterName</th>
<th>LicenseKey</th>
<th>ExpiryDate</th>
<th>YearID</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
</table>
Please assist. Thank you.

So after a lot of research, I got it. I had to change the button function.
$('#datatable tbody').on( 'click', 'button', function () {
var tr = $(this).closest('tr');
var value = $(tr).find('td').eq(0)[0].innerHTML;
alert(value);
return false;
});
If anyone has a better way of doing this, please let me know.

Related

JQuery Datatable Reload From Server MVC

I have a Datatable of JQuery generated at first-page load. I am trying to refresh it according to the selected criteria from the selectlist.
My Datatable initialized first like the following code.
<table class="table table-striped table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Select All <input type="checkbox" class="checkbox" id="chkBoxAll"></th>
#foreach (System.Data.DataColumn col in Model.DataTypesTable.Columns)
{
<th> #col.Caption</th>
}
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.DataTypesTable.Rows)
{
<tr>
<td> <input type="checkbox" class="checkbox" name="chkBox" value="#row.ItemArray[0]"></td>
#foreach (var cell in row.ItemArray)
{
<td>
#cell.ToString()
</td>
}
</tr>
}
</tbody>
</table>
<script>
$(document).ready(function() {
$('#dataTable').DataTable();
});
</script>
It initializes well at first. However, when I try to reload it on the selectlistchange event, it doesn't reload anything and displays an error like this.
DataTables warning: table id=dataTable - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'html',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
console.log(result);
$("#dataTable").DataTable({
destroy: true,
data: result,
columns: [
{ data: "Id", name: "Id" },
{ data: "Data Name", name: "Data Name" },
{ data: "Description", name: "Description" },
{ data: "Device Type", name: "Device Type" }
], columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Controller:
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
var json = this.Json(new { data = dt }/*, _jsonSetting*/);
return json;
}
My data is like below from the developer tools:
Please help me out to resolve the issue... Thanks in advance.
After long tries and losing hairs.. I have found a solution clear and add the rows again instead of destroy command. Here is the solution below.
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'json',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
var dataTable = $("#dataTable").DataTable();
dataTable.clear().draw();
$.each(result, function myfunc (index, value) {
// use data table row.add, then .draw for table refresh
dataTable.row.add([
'<input type="checkbox" class="checkbox" name="chkBox" value="' + value.Id + '">',
value.Id,
value.DataName,
value.Description,
value.DeviceType
]).draw();
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Also, it is important to return a json object from the controller action.
PS. If the Json Object has an initial tag like data, you may need to change the looping value.Id to value.data.Id. But it is better to not use any tag.
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
var json = this.Json(dt , _jsonSetting);
return json;
}

DataTables Reload

Well, I'm trying to do something for the job, where I need a Table made with the DataTables library to be constantly updating, for example, every 10 seconds.
I'm facing very boring problems, what I'm trying to do is give a Reload on API, as described on the official website here: https://datatables.net/reference/api/ajax.reload()
I'm using this:
function AutoReload1()
{
var table = $('#OperationFix').DataTable({
ajax: "data.json"
});
setInterval(function () {
table.ajax.reload();
}, 5000);
//loadOrdersFix();
//alert('Testing')
}
Then it returns the following error to me:
DataTables warning: table id=OperationFix - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
Your code seems to be fine.
But error which you mentioned occurs when AutoReload1(); is called again somehow after its already loaded.
To resolve that you need to either add destroy: true or find out why AutoReload1() is called multiple times.
function AutoReload1()
{
var table = $('#OperationFix').DataTable({
ajax: "data.json",
destroy: true
});
setInterval(function () {
table.ajax.reload();
}, 5000);
}
Working Fiddle
Edit 1:
As per your fiddle, you have defined Datatable 2 places so add destroy:true on both place
var table = $(OperationFixTableId).DataTable({
dom: 'Bfrtip',
pageLength: 1000,
columns: columns,
data: OperationFix,
destroy: true
HTML:
<div class="container">
<table id="OperationFix" class="display" width="100%">
<tfoot>
<tr>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
</tr>
</tfoot>
</table>
</div>
JS:
var OperationFixTableId = $('#OperationFix');
var refreshIntervalId = setInterval;
function AutoReload1()
{
var OperationFixTableId = $('#OperationFix').DataTable({
ajax: 'data.json',
destroy: true
});
setInterval(function () {
OperationFixTableId.ajax.reload();
}, 5000);
}
function AutoReload() {
var checkbox = document.getElementById('myonoffswitch');
if (checkbox.checked == true)
{
AutoReload1();
}
if (checkbox.checked == false)
{
clearInterval(refreshIntervalId);
}
}
I'm currently trying to do this, but when I test it I see that he tries to load my DataTable with 'data.json' what I'd like him to do is load it with what he has in the bank as I could do this, my connection is here:
function GetOrdersFix(startDate, endDate, status, type, onSuccess, onError) {
var uri = executionContext.settings.GetOrdersFix;
var data = {
startDate: new Date(startDate).toJSON(),
endDate: new Date(endDate).toJSON()
};
if (status) { data.status = status; }
if (type) { data.type = type; }
console.info('Loading orders fix from ' + uri);
//Call to server API
$.ajax({
type: 'GET',
url: uri,
data: data,
success: function (responseData, status, jqXHR) {
onSuccess(responseData);
},
error: function (jqXHR, status, errorThrown) {
onError(status + ',' + errorThrown + ',' + jqXHR.responseText);
}
});
}

Autocomplete for textbox Control under HTML table

I have a Html table(instead of Grid control I used HTML table) having multiple rows with one drop down and one textbox control.I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
And Jquery code which I tried is as follows.
$(function () {
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
});
You're saying
having multiple rows with one drop down and one textbox control. I want auto complete function for that text box
and I'm also seeing
$('#Item_Item_Name').autocomplete(...
Are you giving the same id to every textbox? If so, that will not work. Ids have to be unique. Jquery will assume you have only 1 and fire/listen to events only for that 1 textbox.
Consider rewriting your JS using classes for the textbox instead.

under HTML table Autocomplete for HtmlEditor Control

I have a Html table having multiple rows with one drop down and one textbox control.
I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
CODE:
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
Java Script :
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
Your autocomplete() call works only on the elements that are in the dom the time you call it. So for dynamically added elements you'll need the call the function again (after the new row was added).
One more thing to notice is that any call using the element id ($('#Item_Item_Name')) will work only for the first element with that id, because ids are meant to be unique. So you'll need to change the selector to get the input from the new row.
Create a function that inits the autocomplete And after every row you add, call that function on the element you want.
function initAutoComplete(elem) {
$(elem).autocomplete({ /* the same as you use now */ });
}
// after you addded the new row
initAutoComplete($(newRow).find('.autocopmlete-input'));

Add child row as nested datatable within exisiting datatable

I have a datatable that lists a number of 'stages' (which relate to work employment procedures being carried out against the individual employee).
I have managed to code this so the table can display child rows. I want each child row to display another datatable which will list associated tasks for the selected stage.
So far I have managed to add and display a child row with the table header. See here:
[Child Row][1]
My HTML is as follows:
<div class="table-responsive">
<table class="table table-hover " id="stage_datatable">
<thead>
<tr>
<th>Select</th>
<th><!-- Detail --></th>
<th>ID</th>
<th>Stage</th>
<th>Title</th>
<th>Desc</th>
<th>Date/Time</th>
<th>Location</th>
<th>Rep Required</th>
<th>Logged By</th>
<th>Date Logged</th>
</tr>
</thead>
</table>
The Jquery for my stage table is here:
function loadStageTable (action, id) {
$.ajax ( {
url: './stages/stage_ajax.php',
method: 'GET',
data: {action: action, id:id}, // id could be taskID or caseID
dataType: 'json',
success: function (data) {
console.log(data);
console.log("success");
iTableCounter = 0;
var table = $('#stage_datatable').DataTable ( {
"searching": false,
"sort": false,
data:data,
select: {
style: 'os'
},
responsive: true,
columns: [
{ 'data': null },
{
"data": null,
"className": 'details-control',
"orderable": false,
"defaultContent": ''
},
{ 'data': 'meeting_id' },
{ 'data': 'stage_desc' },
{ 'data': 'meeting_title' },
{ 'data': 'meeting_desc' },
{ 'data': 'meeting_date_time' },
{ 'data': 'meeting_location' },
{ 'data': 'rep_required' },
{ 'data': 'logged_by' },
{ 'data': 'start_date' }
],
"columnDefs": [ {
"targets": -11,
"data": null,
"defaultContent": "<button class='btn btn-xs btn-primary'>Select</button>"
},
{
"targets": -3,
"className": "dt-body-center",
"render": function (data, type, full, meta){
var is_checked = data == true ? "checked" : "";
return '<input type="checkbox" class="checkbox" ' + is_checked + ' disabled />';
}
}]
});
console.log("stage datatable processed");
$('#stage_datatable tbody').on('click', 'td.details-control', function () {
var tr = $(this).parents('tr');
    var row = table.row( tr );
    if ( row.child.isShown() ) { // Close this row if already open
$('div.slider', row.child()).slideUp( function () {
row.child.hide();
tr.removeClass('shown');
} );
    }else {
// table id is required for child rows and will be unique
iTableCounter = iTableCounter + 1
row.child(getChildRow).show(); // call getChildRow function to obtain the child row html
var caseID = localStorage.getItem('caseID');
console.log(caseID);
loadMyTaskTable('get case tasks', caseID); // this is the AJAX function invoked to retrieve tasks. THIS DOESN'T WORK
tr.addClass('shown');
$('div.slider', row.child()).slideDown("slow");
    }
});
},
failure: function (data) {
console.log ("failed");
}
});
In the above I have coded an event that triggers the child row to be inserted:
$('#stage_datatable tbody').on('click', 'td.details-control', function () {
var tr = $(this).parents('tr');
var row = table.row( tr );
if ( row.child.isShown() ) { // Close this row if already open
$('div.slider', row.child()).slideUp( function () {
row.child.hide();
tr.removeClass('shown');
} );
}else {
// table id is required for child rows and will be unique
iTableCounter = iTableCounter + 1
row.child(getChildRow).show(); // call getChildRow function to obtain the child row html
var caseID = localStorage.getItem('caseID');
console.log(caseID);
loadMyTaskTable('get case tasks', caseID); // this is the AJAX function invoked to retrieve tasks
tr.addClass('shown');
$('div.slider', row.child()).slideDown("slow");
}
});
The getChildRow is as follows:
function getChildRow() {
var x = innerTaskTableTemplate(iTableCounter, taskTableTemplate());
return x;
}
The taskTableTemplate parameter is as follows:
function taskTableTemplate() {
return '<thead>'+
'<tr>'+
'<th>Select</th>'+
'<th>ID</th>'+
'<th>Task Title</th>'+
'<th>Desc</th>'+
'<th>Due Date/Time</th>'+
'<th>Allocated To</th>'+
'<th>Logged By</th>'+
'<th>Date Logged</th>'+
'</tr>'+
'</thead>'+
'<tbody></tbody>';
}
And the innerTaskTableTemplate function is as follows:
function innerTaskTableTemplate(tableID, html) {
var sOut = "<div class='slider'><table id='task_table_" + tableID + "'>";
sOut += html;
sOut += "</table></div>";
console.log(sOut);
return sOut;
}
IF I OMIT THIS LINE from my **loadStageTable ** function then the code successfully adds a child row and inserts the table html.
loadMyTaskTable('get case tasks', caseID);
However, if I include the line then the child row seems to disappear. If I inspect the DOM using firebug I can't find my child row (e.g. 'task_table_1'). See [here][2].
The loadMyTaskTable function is as follows:
function loadMyTaskTable (action, id) {
$.ajax ( {
url: './tasks/task_ajax.php',
method: 'GET',
data: {action: action, id:id}, // id could be taskID or caseID
dataType: 'json',
success: function (data) {
console.log(data);
var taskTable = $('#task_table_1')
$(taskTable).DataTable ( {
data:data,
select: {
style: 'os'
},
responsive: true,
columns: [
{ 'data': null },
{ 'data': 'task_id' },
{ 'data': 'task_title' },
{ 'data': 'task_desc' },
{ 'data': 'task_due_date' },
{ 'data': 'allocated_to' },
{ 'data': 'logged_by' },
{ 'data': 'start_date' }
],
"columnDefs": [ {
"targets": -8,
"data": null,
"defaultContent": "<button class='btn btn-xs btn-primary'>Select</button>"
}]
});
console.log("task table successfully loaded");
},
failure: function (data) {
console.log ("failed");
}
});
}
Please can you let me know where I am going wrong. i am confident that my AJAX is working fine as I've tried adding the task table html onto the main page and it loads properly this way, but not when I dynamically insert it as a child row in my datatable.
I have tried looking at similar other posts (e.g. [click here][3]) but I think that the code has since been superseded by the datatables new API.
Many thanks.
Additional Detail
I have debugged the script and found the following:
The script successfully inserts the child row with the task_table_1 html
The child row is subsequently removed from the DOM once it hits the *console.log("task table successfully loaded"); * line in my loadMyTaskTable function.
Am still not sure what I am doing wrong here.

Categories