I'm trying to add data to a table dynamically through JavaScript, and it returns this:
Uncaught TypeError: Cannot read property 'add' of undefined.
EDIT: The code works perfectly without the row.add line.
Relevant code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="./css/jquery.dataTables.min.css">
<script type="text/javascript" src="./lib/jquery.min.js"></script>
<script type="text/javascript" src="./lib/jquery.dataTables.min.js"></script>
<script>
var dataSet = [
['1.1','2.1'],
['1.2','2.2'],
];
$(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
t = $('#example').dataTable(
{
data: dataSet,
columns: [
{ "title": "Col 1" },
{ "title": "Col 2" },
],
});
t.row.add(['1.3', '2.3']) // <-- Fails
});
</script>
</head>
<body>
<div id="demo" style="width:500px"> </div>
</body>
</html>
You are very close. Here is the change I have done to your code:
a. While initializing DataTable, used capital D.
b. Used .draw(); while adding row.
var dataSet = [
['1.1','2.1'],
['1.2','2.2']
];
$(document).ready(function() {
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
var t = $('#example').DataTable({
data: dataSet,
columns: [
{ "title": "Col 1" },
{ "title": "Col 2" }
]
});
t.row.add(['1.3', '2.3']).draw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<div id="demo" style="width:500px"></div>
Related
Why does my javascript just show the first row from the table on Highcharts and not the other rows?
Everything works fine except highcharts only shows data of the first row on the graph and not all rows.What am I missing?
http://live.datatables.net/febayaxa/10/edit
Please see the code below. Thanks in advance.
$(document).ready(function() {
var tableData = [];
var tableCategories = [];
var table = $("#example1").DataTable({
initComplete: function(settings, json) {
let api = new $.fn.dataTable.Api(settings);
// get the seris data as an array of numbers from the table row data:
api.rows().data().toArray()[0].forEach(function(element, index) {
if (index > 0) {
tableData.push(parseFloat(element.replace(/,/g, '')));
}
});
// get the x-axis caregories from the table headings:
api.columns().header().toArray().forEach(function(element, index) {
if (index > 0) {
tableCategories.push($(element).html());
}
});
}
});
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: tableCategories
},
series: [{
data: tableData
}]
});
});
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example1" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
<tr ><td> Data</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr></tbody>
<tr ><td> Data</td><td>8,000</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr></tbody>
</tbody></table>
I have a >50000 SharePoint Online document library list being rendered using the working code below. The page load time is close to 10-15 seconds.
I tried to implement server side processing to reduce page load times, but it made no difference:
"processing": true, "serverSide": true,
<!DOCTYPE html>
<html">
<head>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/jquery-3.5.1.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/moment.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/datetime-moment.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/jszip.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/pdfmake.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/vfs_fonts.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/buttons.print.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/dataTables.searchBuilder.min.js"></script>
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/dataTables.jqueryui.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/buttons.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/searchBuilder.dataTables.min.css">
<script>
$(document).ready(function() {loadItems();});
function loadItems() {
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
var oDataUrl = siteUrl + "/_api/web/lists/getbytitle('LIST_NAME')/items?$top=200000&$select=Created,ATA,EncodedAbsUrl";
$.ajax({
url: oDataUrl,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
try {
$('#table_id').DataTable({
"pageLength": 100,
"dom": 'Bfrtip',
"buttons": [ {extend: 'searchBuilder', config: {columns: [0,1,2,3,4,5,6,7],},}, 'copy', 'csv', 'pdf', {extend: 'print',exportOptions: {columns: [ 0, 1, 2, 3, 4, 5, 6, 7 ]}} ],
"aaData": data.d.results,
"aaSorting": [[0, "desc"]],
"aoColumns": [
{
"mData": "Created"
},
{
"mData": "ATA"
},
{
"mData": "EncodedAbsUrl",
"mRender": function ( data, type, full )
{return 'View';}
}
]
});
} catch (e) {
alert(e.message);
}
}
function myErrHandler(data, errMessage) {
alert("Error: " + errMessage);
}
</script>
</head>
<body>
<div>
<table id="table_id" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Uploaded</th>
<th>ATA</th>
<th></th>
</tr>
</thead>
</table>
</div>
</body>
</html>
You have to set backend code because serverside means you have to handle Datatable rows on server on each action on client side (change page , filter , search , ...)
For more informations here : https://datatables.net/examples/data_sources/server_side
My JQuery code is not filtering or searching the JSON array, however, it is pretty much the same code on w3schools. But I am not getting any error. Is there a way to get this to work?
I needed it to search through the JSON array and return the values.
////////////////////////////////////////////
The JSON:
[
{
"ID": 1,
"Station": "Carmichael Rd.",
"Address": "54 Myers Rd.",
"Monthly_CStore_Sales": "120,000",
"Operator": "Michael Sears",
"Top_SKU": "Hotdogs"
},
{
"ID": 2,
"Station": "Baillou Hill",
"Address": "564 Jackson Ave.",
"Monthly_CStore_Sales": "89000",
"Operator": "Sarah Pikes",
"Top_SKU": "Patties"
},
{
"ID": 3,
"Station": "Oakesfield",
"Address": "42 Peterson St.",
"Monthly_CStore_Sales": "150000",
"Operator": "Yolanda Gray",
"Top_SKU": "Chicken"
},
]
The HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<p><br></br></p>
<div class="container">
<input type="search" class="form-control" id="search"></div></br>
<table class="table table-striped table-bordered table-hover"></table>
<thead>
<tr>
<th>ID</th>
<th>Station</th>
<th>Address</th>
<th>Monthly_CStore_Sales</th>
<th>Operator</th>
<th>Top_SKU</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
The Javascript:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$('#search').keydown(function(){
$.getJSON("smallData.json",function(data){
var search = $('#search').val();
var regex = new RegExp(search,'i');
var output;
$.each(data, function(key, val){
if((val.ID.toString().search(regex) != -1) || (val.Station.toString().search(regex) != -1)){
output += "<tr>";
output += "<td id='"+key+"'>"+val.ID+"</td>";
output += "<td id='"+key+"'>"+val.Station+"</td>";
output += "<td id='"+key+"'>"+val.Address+"</td>";
output += "<td id='"+key+"'>"+val.Monthly_CStore_Sales+"</td>";
output += "<td id='"+key+"'>"+val.Top_SKU+"</td>";
output += "</tr>";
}
});
$('tbody').html(output);
});
})
</script>
I've been able to get a JSON file to load into a table fine, but I want to have multiple JSON files and change which one is loaded into the table based on which button has been pressed. I thought I could just make it change the variable data, but then the table still stays the same (I'm assuming you have to make it refresh some how?).
Also, on a side note, is it possible to have the prices have a space between them?
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<meta name="description" content="Hello World">
<!-- Latest compiled and minified CSS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://rawgit.com/wenzhixin/bootstrap-table/master/dist/bootstrap-table.min.css">
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/dist/bootstrap-table.min.js"></script>
<script src="data1.json"></script>
<script src="data2.json"></script>
<script>
$(function () {
$('#table').bootstrapTable({
data: data_one
});
$('#data1').on('click', function(event) {
$('#table').bootstrapTable({
data: data_one
});
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable({
data: data_two
});
});
});
</script>
</head>
<body>
<header>
<div class="jumbotron">
<div class="container">
<h3>Test</h3>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="text-center">
<a class="btn btn-large btn-success" id="data1">Data 1</a>
<a class="btn btn-large btn-success" id="data2">Data 2</a>
</div>
</div>
</div>
<div class="container">
<div class="row">
<table id="table" class="table table-bordered" data-search="true" data-show-toggle="true">
<thead>
<tr>
<th data-field="id" data-sortable="true">ID</th>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="prices" data-sortable="true">Price</th>
</tr>
</thead>
</table>
</div>
</div>
<footer>
<div class="container">
<hr>
<p><small>Google didn't help me</small></p>
</div>
</footer>
</body>
</html>
data1.json:
var data_one = [
{
"id": 0,
"name": "test0",
"prices": [
"$0",
"$5"
]
},
{
"id": 1,
"name": "test1",
"prices": [
"$4",
"$1"
]
},
{
"id": 2,
"name": "test2",
"prices": [
"$2",
"$3"
]
},
];
data2.json:
var data_two = [
{
"id": 4,
"name": "test4",
"prices": [
"$1",
"$2"
]
},
{
"id": 5,
"name": "test5",
"prices": [
"$6",
"$5"
]
},
{
"id": 6,
"name": "test6",
"prices": [
"$9",
"$7"
]
},
];
You need to specify the 'load' method when updating the data in the table:
<script>
$(function () {
$('#table').bootstrapTable({ data: data_one });
$('#data1').on('click', function(event) {
$('#table').bootstrapTable('load', { data: data_one });
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable('load', { data: data_two });
});
});
</script>
For some reason you cannot initially load the data with load method, only update. You can also append data with "append" method and do lot of cool stuff. Check out the documentation here: Bootstrap Table Documentation
1) You don't need all the ready functions, just one (the functions that look like $(function () {..}).
2) Also, you're not calling the plugin on that element again when you click a button - you have to explicitly do that.
3) Finally, you've not added an event listener to your second button - you added a duplicate listener to your first button.
4) You should remove the inline onclick="data1()" and onclick="data2()" from your HTML buttons.
$(function () {
$('#table').bootstrapTable({
data: data_one
});
$('#data1').on('click', function(event) {
$('#table').bootstrapTable({
data: data_one
});
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable({
data: data_two
});
});
});
You are not integrating data2() function. You can write your code as below.
$(function () {
$('#table').bootstrapTable({
data: data_one
});
});
function data1(){
$('#table').bootstrapTable({
data: data_one
});
}
function data2(){
$('#table').bootstrapTable({
data: data_two
});
}
I am using the jQuery DataTable for creating a web page. I have a use case where the page opens with the table already populated. Now, there is a form in the page where he can put some filters and refresh the table. Also, more importantly for each row, I can expand to see more details as explained here.
In my case, as soon as the data is reloaded after the form is submit, the details button which would expand each data row stops working. It gives the following error:
jquery.dataTables.min.js:120 Uncaught TypeError: Cannot read property '_detailsShow' of undefined
I am reloading thee table by first clearing, destroying and then calling the DataTable method. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="../../../static/css/chosen/bootstrap-chosen.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../../../static/js/bootstrap/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(
function ()
{
var dashboard_table_id = "#example";
function destroy_existing_data_table()
{
var existing_table = $(dashboard_table_id).dataTable();
if (existing_table != undefined)
{
existing_table.fnClearTable();
existing_table.fnDestroy();
}
}
function create_dashboard_table()
{
var data_table = $(dashboard_table_id).DataTable({
"data": [{
"dt_RowId": 10,
"column1": "delhivery",
"column2": "CRP12345",
"column3": "1122",
"column4": "One expanded row"
}, {
"dt_RowId": 2,
"column1": "delhivery",
"column2": "CRP12345",
"column3": "1122",
"column4": "Other expanded row"
}],
"columns": [
{"className": "select-checkbox", orderable: false, "data": null, "defaultContent": ""},
{"class": "details-control", "orderable": false, "data": null, "defaultContent": ""},
{"data": "column1"},
{"data": "column2"},
{"data": "column3"}
],
"buttons": {},
"dom": 'lBfrtip',
"select": {
"style": 'multi',
"selector": 'td:first-child'
},
"oLanguage": {"sSearch": ""},
"order": [[2, 'asc']],
"bLengthChange": false,
"pageLength": 25
});
// adding event listener for opening and closing details
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',
function ()
{
var tableRow = $(this).closest('tr');
var row = data_table.row(tableRow);
if (row.child.isShown())
{
tableRow.removeClass('details');
row.child.hide();
}
else
{
var rowData = row.data();
tableRow.addClass('details');
row.child("Hello there, this is the expanded view I am referring to....").show();
}
});
}
$("#example-form-submit").click(function (event)
{
event.preventDefault();
destroy_existing_data_table();
create_dashboard_table();
});
create_dashboard_table();
});
</script>
<style>td.details-control {
background: green;
cursor: pointer;
}
tr.details td.details-control {
background: blue;
}</style>
</head>
<body>
<div class="main-content lfloat">
<div class="container" style="width: 100%;">
<label for="example-form-submit" class="col-md-2 control-label"></label>
<div class="col-md-2">
<button type="submit" id="example-form-submit" class="btn btn-primary">Refresh and try to expand</button>
</div>
<div>
<table id="example" class="row-border hover order-column" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th>column1</th>
<th>column2</th>
<th>column3</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</body>
</html>
Can some one please point out what I am doing wrong. Thanks a ton in advance. This has been bugging me for some time now.
JSFiddle : Credits: #Edis Golubich
it works for me. just remove the latest click event handler by add .off before add the new one.
$(dashboard_table_id).find('tbody').off('click', 'tr td.details-control');
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',function(){...});
The issue is that the data_table object is not getting 'updated' when using jQuery.on() via delegated event handling.
Try this: https://jsfiddle.net/f5mdcrup/4/
What I did was declare data_table outside of the function. The scope will be different in this case.
Following code works for me
$(dashboard_table_id).find('tbody').off('click', 'tr td.details-control');
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',function(){
//Action To perform
});