var clientTable = $("#table").DataTable();
clientTable.row.add([1,1,1,1]).draw(false);
I add new row in my datatable with this code but I need to add row in first position of the table.
How can I do this ?
According to the documentation "The rows that are added are subjected to the ordering and search criteria that are applied to the table, which will determine the new row's position and visibility in the table" - so, the new row's position in the table is dependent on the data. If you apply a sort ordering to the table, the new row may be added first - depending on the data. If you don't have a column that would fit for that, you can add a hidden column with a counter and sort by that (see the below snippet for example).
Alternately, you can consider using the RowReorder extension
$(document).ready(function() {
var t = $('#example').dataTable( {
'columns': [
{'title': 'id', 'visible': false},
{'title': 'data'}
],
'order' : [[1,'desc']]
} );
var counter = 1;
$('#addRow').on( 'click', function () {
t.api().row.add( [
counter,
'data for id: ' + counter
] ).draw( false );
counter++;
} );
// Automatically add a first row of data
$('#addRow').click();
} );
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
</head>
<button id="addRow">Add New Row</button>
<table id="example" class="display" width="100%" cellspacing="0" />
</html>
Actualy, is not possible with DataTable default function.
Do it with jQuery :
$('#tableName tr:first').after("<tr role="row"><td></td><td>Your Row</td></tr>");
Related
This question already has an answer here:
Odd behavior of datatables.search function after modifying it
(1 answer)
Closed 4 years ago.
There are already several questions here on SO on this subject, however none is about my exact situation.
I have a datatable with 2 columns, one contains text input field and the other a select. The current behavior of datatables' search functionality is to search in the entire select HTML. The behvior I want is search only the chosen option.
I'm aware we can override/intercept the search/filter events, ie
$('#mapping-table_filter input', data_table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function (e) {
data_table.search(...).draw();
});
// or
data_table.on('search.dt', function () {
});
But this does not help since .search does not accept a callback.
JSFiddle
https://jsfiddle.net/0oabx2mr/
If you search for any of "first", "second" or "third" both rows are still visible. I want to be able to search for "second" and "third" and only get the relevant row.
With slight architecture changes, your example may look like that:
var srcData = [
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption']
];
var dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [{
title: 'Options',
render: (data, type, row) => '<select>'+row.reduce((options, option) => options += `<option value="${option}">${option}</option>`,'')+'</select>'
}]
});
var needle = null;
$.fn.DataTable.ext.search.push(
(settings, row, index) => $(dataTable.cell(`:eq(${index})`,':eq(0)').node()).find('select').val().match(needle) || !needle
);
$('#search').on('keyup', event => {
needle = $(event.target).val();
dataTable.draw();
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<input id="search"></input>
<table id="mytable"></table>
</body>
</html>
I'm a newbie to jQuery, so, please, don't judge me for my dumb question.
What I'm trying to achieve is fill datatable with exchange rates, sourced by API.
So, I managed to construct datatable, but its body is empty and there're no errors in the console, it's just "loading..." message where my data is supposed to be.
Searching for similar topics just didn't get any results. I would be thankful for your help, because I'm banging my head against that wall for 2 days already.
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="rates"></table>
</body>
var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';
var dataTable = $('#rates').DataTable({
sDom: 't',
ajax: {
url: url + key
},
columns: [{
title: 'currency'
},{
title: 'rate'
}]
});
Seems like your data is structured improperly. Each data entry must correspond to DataTables row, so your code should be something like:
var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';
var dataTable = $('#rates').DataTable({
sDom: 't',
ajax: {
url: url+key,
dataSrc: function(data){
let apiData = [];
$.each(data.rates, function(index, entry){
apiData.push({currency:index, rate:entry});
});
return apiData.slice(0,10);
}
},
columns: [
{title:'currency', data:'currency'},
{title:'rate', data:'rate'}
]
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="rates"></table>
</body>
</html>
I am a newbie of using fancytree. I have created a demo to display data in a table within a webpage. Now I hope to collect the data back after users updated them.
I was using so called tree methods as mentioned in the tutorial. There is an example that has two lines below:
var tree = $("#tree").fancytree("getTree");
alert("We have " + tree.count() + " nodes.");
I thought I can use the fancytree instance, the variable 'tree' in the above example, to access all nodes so that to collect the values they take. But when I put this two-lines example into my codes, I got errors.
For making it clear, I pasted the complete code below. Close to the end of the code, there are two comments marked by Place_1 and Place_2. When I put the two-lines example in each of these two places, I got errors, which are "Uncaught TypeError: undefined is not a function", or "Uncaught Error: cannot call methods on fancytree prior to initialization; attempted to call method 'getTree'" respectively.
I thought I must missed something. Any idea will be helpful. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<link type="text/css" rel="stylesheet" href="addtionals/jquery-ui.css" />
<script src="addtionals/jquery.min.js" type="text/javascript"></script>
<script src="addtionals/jquery-ui.min.js" type="text/javascript"></script>
<link href="fancytree/src/skin-win8/ui.fancytree.css" rel="stylesheet" type="text/css">
<script src="fancytree/src/jquery.fancytree.js" type="text/javascript"></script>
<script src="fancytree/src/jquery.fancytree.edit.js" type="text/javascript"></script>
<script src="fancytree/src/jquery.fancytree.table.js" type="text/javascript"></script>
<script type="text/javascript">
var Rigid_Package_SOURCE = [
{title: "Role-Based Statements", key: "1", folder: true, expanded: true, children: [
{title: "Text1", key: "2"},
{title: "Text2", key: "3"}
]}
];
$(function(){
$("#RB_Statements_tree").fancytree({
source: Rigid_Package_SOURCE,
extensions: ["edit", "table"],
edit: {
triggerCancel: ["esc"],
triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
beforeEdit: function(event, data){
if (data.node.isFolder() ) {
var title = data.node.title;
data.node.editEnd();
data.node.setTitle(title);
return false;
}
},
beforeClose: function(event, data){
if (data.node.isFolder()) {
}else{
if (data.input.val() == ""){
data.node.setTitle("");
}
}
}
},
table: {
indentation: 20,
nodeColumnIdx: 1
},
renderColumns: function(event, data) {
var node = data.node,
$tdList = $(node.tr).find(">td"),
$select = $("<select />");
if( node.isFolder() ) {
}else{
$("<option > Tutor </option>").appendTo($select);
$("<option selected > Student </option>").appendTo($select);
$("<option > Teacher </option>").appendTo($select);
$tdList.eq(0).html($select);
}
}
});
});
</script>
</head>
<body>
<script type="text/javascript">
//Place_1: Uncaught TypeError: undefined is not a function
//var tree = $("#RB_Statements_tree").fancytree("getTree");
//alert("We have " + tree.count() + " nodes.");
</script>
<!--The title of this page-->
<h4> Vicarious Conversation</h4>
<!-- Table: Role-Based Statements -->
<table id="RB_Statements_tree">
<colgroup>
<col width="100px">
<col width="300px">
</colgroup>
<thead>
<tr> <th></th> <th></th>
</thead>
<tbody>
</tbody>
</table>
<br>
<script type="text/javascript">
//Place_2: Uncaught Error: cannot call methods on fancytree prior to initialization; attempted to call method 'getTree'
//var tree = $("#RB_Statements_tree").fancytree("getTree");
//alert("We have " + tree.count() + " nodes.");
</script>
</body>
</html>
Thanks for the suggestion from Chase.
I think the two-lines example should be added into somewhere after the initialization has been finished.
For example, I added the codes into a button's body and it works well. Here is the example about implementing a button in fancytree: http://wwwendt.de/tech/fancytree/demo/#sample-source.html
When using list.js and tabletop for a sortable table taken from a Gdoc, I get the error: "Uncaught TypeError: Cannot read property 'childNodes' of undefined" on the first line of list.js.
Because the website I work for can only have JS uploaded, I need to write all my html using js or jquery, so it's a bit wonky. I think the error is being thrown because of the order I have everything, but I have tried moving things around to no avail. Everything is working other than the sorting.
Thanks!
HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="list.js-master/dist/list.min.js"></script>
<script type="text/javascript" src="src/tabletop.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="tablesetter"></div>
</body>
<script type="text/javascript">
var url = 'url to gdoc here';
$(document).ready( function(){
Tabletop.init( {key: url, callback: showInfo, parseNumbers: true} )})
function showInfo(data, tabletop){
$("#tablesetter").append('<h2>Table Working</h2><table><thead><th class="sort" data-sort="university">University</th><th class="sort" data-sort="no">Billionaires</th><th class="sort" data-sort="no2">Billionaires Rank</th><th class="sort" data-sort="rank">U.S. News Rank</th></thead><tbody class="list"></tbody></table>');
$.each(tabletop.sheets("Sheet1").all(), function(i, cat){
var htmltable = $('<tr><td class="university">' + cat.university + '</td>');
htmltable.append('<td class="no">' + cat.numberofbillionaires + '</td>');
htmltable.append('<td class="no2">' + cat.rankedbybillionaires + '</td>');
htmltable.append('<td class="rank">' + cat.usnewsranking + '</td></tr>');
htmltable.appendTo("tbody");
})
}
</script>
<script type="text/javascript" src="options.js"></script>
</html>
JS file
var options = {
valueNames: [ 'university', 'no' , 'no2' , 'rank']
};
var userList = new List('tablesetter', options);
The problem
var userList = new List('tablesetter', options); should be executed when the dom has an element of the list class; since in the question's code the list class default to list" , so such element should be <tbody class="list"> that is going to be appended to the #tablesetter only when the showInfo function receive data from google.
The solution
We ensure that the var userList = new List('tablesetter', options) statement executes after ( ie: at the end ) of the showInfo function; in other words move var userList = new List('tablesetter', options); from options.js just before the closing right bracket of the showinfo function.
More details
in the question's code when list.js tries to init() the dom is:
and list.list is still undefined when list.js defines it's getItemSource() functions:
with the proposed fix, at the var userList = new List('tablesetter', options); the dom is like:
and when defines it's getItemSource() functions the list.list can use the tbody as aspected:
If you look at this post, I'm sure your just missing some of the minimum requirements for list.js to function properly. Try to dynamically add the input with id and class of "search" as well with your other classes. Let me know if this helps.
https://stackoverflow.com/a/23078200/4812515
I am writing a page with multiple jqGrids. My code follows a JavaScript MVC pattern which is going to provide an API for my HTML elements (including jqGrids). So, in the end of the day, I can create grids by calling my API. Something like:
var grid1 = new grid();
grid1.init();
var grid2 = new grid();
grid2.init();
I have done it with other javascript components and it worked great. However, when I create multiple jqGrid instances on the same page there is only one jqPager on the page attached to the last grid. Does anybody have an idea why?
Here is my code (Note that this is a simplified version, in reality I keep it separated in different .js files and also follow many other design patterns):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/redmond/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/css/ui.jqgrid.css" />
</head><body>
<!-- IMPORT JS -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/js/jquery.jqGrid.min.js"></script>
<script>
$(document).ready(function() {
function grid() {
//=== LOCA VARIABLES ===//
var myGrid = $('<table>').attr( "id", "useraccount-search-datagrid");
var myPager = $("<div>").attr("id", "useraccount-search-datagrid-pager");
var localData1 = {
"page" : 1,
"totalRecords" : 5,
"pageSize" : 3,
"rows" : [
{ Name : "Name 1"},
{ Name : "Name 3"},
{ Name : "Name 2"}
]
};
function publicInit(){
$("body").append(myGrid, myPager);
myGrid.jqGrid({
pager : myPager,
data: localData1.rows,
datatype : "local",
colModel : [
{ name : 'Name', index : 'Name', width : "500"}
],
localReader: {
repeatitems: false
},
rowNum : 3,
viewrecords : true,
height : "auto",
ignoreCase : true
});
}
//=== REVEALING PATTERN===//
return {
init: publicInit
}
};
var grid1 = new grid();
grid1.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid();
grid2.init();
});
</script>
</body>
</html>
Any help would be highly appreciated.
It seems to me that your code produce <table> and <div> elements with the same id attributes. So the second grid var grid2 = new grid(); just add <table> and <div> elements which already exist on the page. It's a bug. All id attributes of all element on one HTML page must be unique. So the lines myGrid = $('<table>').attr( "id", "useraccount-search-datagrid"); and var myPager = $("<div>").attr("id", "useraccount-search-datagrid-pager"); must be changed.
If you need just to assign some unique ids you can use $.jgrid.randId() method used in jqGrid internally. The code could be
var myGrid = $("<table>").attr("id", $.jgrid.randId());
var myPager = $("<div>").attr("id", $.jgrid.randId());
Moreover I strictly recommend you to use name conversion used in JavaScript. If you need to use new operator to create an object you should rename the function grid to Grid.