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;
}
Related
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.
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.
I have a predefined datatable on my page that is populating from data with an ajax call. After these values are on the page the user needs an ability to add rows by clicking a button, kind of like an audit log. However, every time I go to add a row I get the error
"DataTables warning: table id=DataTables_Table_0 - Requested unknown
parameter 'data1' for row 2, column 0."
I have been up and down the internet and cannot figure this out. Help please.
I have the table variable defined globally so everyone has access to it
var escalationTable;
and then a function that calls my ajax to populate said table.
function populateTable(var1, var2, var3, var4, var5, var6, var7) {
$.ajax({
dataType: 'json',
//data: id,
type: 'GET',
async: false,
url: baseUrl + 'rest/partUrl/action?var1=' + var1 + '&var2=' + var2 + '&var3=' + var3 + '&var4=' + var4,
success: function (data) {
if (data) {
escalationTable = $('.escalationTable').DataTable({
data: data,
columns: [
{
data: "data1" ? "data1" : null
},
{
data: "data2" ? "data2" : null
}, {
data: "data3" ? "data3" : null
}
],
bSort: false
});
}
},
error: function (request, status, error) {
showErrorMessage(request);
}
});
}
html
<table class="table escalationTable col-md-12" style="width:100%;">
<thead>
<tr>
<th name='esId' scope="col">#</th>
<th name='esUser' scope="col">User</th>
<th name='esDate' scope="col">Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and then my click looks like this
$('.assignToSelf').on('click', function () {
var rowNode = escalationTable
.row.add({
"esId": 'ffffff',
"esUser": 'dfsdfsdf',
"esDate": 'fffff'
})
.draw(false)
.node();
})
The answer to this question would be naming the fields in the add the same as the data that is going into the field. Not based on the name of the field.
$('.assignToSelf').on('click', function () {
var rowNode = escalationTable
.row.add({
"data1": 'ffffff',
"data2": 'dfsdfsdf',
"data3": 'fffff'
})
.draw(false)
.node();
})
This is my code in Razor view that basically displays the table by extracting information from database -
#model List<EmpoyeeInfo.Models.FFX_HR_Employees>
#using System.Reflection;
#{
ViewBag.Title = "Employee Information";
var Properties = Model[0].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
string[] head = new string[Properties.Count()];
}
<div id="web-top">
<div id="horizontal-line"></div>
<input class="search-box-text" type="text" spellcheck="false" placeholder="Search Individual Record..." title="Search Individual Record" id="searchbox" name="searchbox" />
</div>
<div id="web-main">
<table class="employee-info">
<tr>
#foreach (var Property in Properties)
{
if (Property.Name.Equals("AnnualHolidayEntitlement"))
{
<th colspan="2">#Property.Name</th>
}
else
{
<th>#Property.Name</th>
}
}
</tr>
#foreach(var Row in Model)
{
<tr>
#{
Type type = Row.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
}
#foreach (PropertyInfo prop in props)
{
if (prop.Name.Equals("AnnualHolidayEntitlement"))
{
<td contenteditable="true">#prop.GetValue(Row, null)</td>
}
else
{
<td>#prop.GetValue(Row, null)</td>
}
}
<td class="saveToDB">SAVE</td>
</tr>
}
</table>
</div>
but as i type in the search box text, an ajax calls are made -
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (result) {
//do stuff;
},
error: function () {
console.log("no display");
}
});
}
now how do i reload the div - "web-main" and update the Model value such that as the user searches for a name, the table also needs to be updated.
Code below will append the results to the div 'web-main'. You need to manipulate the success portion of jQuery in your code
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (data) {
//do stuff;
console.log(data);
$("web-main").append(JSON.stringify(data));
},
error: function () {
console.log("no display");
}
});
}
In dropdownlist onchange event call FillSystem() Ajax Request is sent but scopeId selector do not run this below method.
function FillSystem() {
var _scopeId = $('#ScopeId').val();
var _roleId = $('#Role_Id').val();
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId").html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId").append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
<table class="table w3-striped w3-border w3-card-4" style="width: 65%">
<tr>
<td>
Scope
</td>
<td>
#Html.DropDownList("ScopeId", null,"--Please Select--", new { style = "width:250px", #onchange = "FillSystem()" })
</td>
</tr>
<tr>
<td>System</td>
<td>
#Html.DropDownList("SystemId", null, "--please select--", new { style = "width:250px" })
</td>
</tr>
</table>
you use DropDown in table and probably multiple row exist, and multiple id with same, your $('#ScopeId') selector, select first element with ScopeId.
first remove #onchange = "FillSystem()" from DropDownList, then try this code
(function ($) {
function FillSystem() {
var _scopeId = $(this).val();
var _roleId = $('#Role_Id').val();
var $row = $(this).closest("tr");
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId", $row).html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId", $row).append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
$(function () {
$("table").on("change", "#ScopeId", FillSystem)
});
}(jQuery));