I am using jquery plugin DataTables for building nice table
var table = $('#example').DataTable({
"data": source
});
I would like that make an each for all rows in table
Unfortunately this way may be out of date and does't work with new version (it launchs an error)
$(table.fnGetNodes()).each(function () {
});
And this way only works only for visibles rows (10 first rows because other rows are paginated)
table.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );
Do you known how to loop to all rows please?
I finally found:
var data = table.rows().data();
data.each(function (value, index) {
console.log(`For index ${index}, data value is ${value}`);
});
Datatables have an iterator for each row rows().every() with this referring to the context of the current row being iterated.
tableName.rows().every(function(){
console.log(this.data());
});
If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...
table.fnGetNodes(); // table is the datatables object.
So we can loop through the rows by using .each() method provided by jQuery.
jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.
});
for example, this data has three fields UserID, UserName and isActive and we want to show only active users
The following code will return all the rows.
var data = $('#myDataTable').DataTable().rows().data();
We will print only active users
data.each(function (value, index) {
if (value.isActive)
{
console.log(value.UserID);
console.log(value.UserName);
}
});
Related
I got a project require angularjs datatable (i-lin) to populate large amount of data. Therefore, i decided to use server side processing and Ajax call to get my PHP data populate into the angularjs datatable. Currently, i could show the static columns and data perfectly however.......
Problem
The Ajax(api call) needs sometime to request the data therefore now my page will show the static data columns first. A few seconds later, page will refresh again then append the new columns.
Which means, user will see the static datatable columns first, After 1 second will see another datatable. It looks very weird for user.
Target
Instead of show the static columns, I would like ensure all data has been returned from Ajax then only show the complete table.
Code
html
<table id="saleReport"
class="report-table table-striped table table-bordered
table-condensed table-hover data-table"
datatable="" dt-options="dtOptions" dt-columns="dtColumns"
dt-instance="dtInstance">
Angularjs
The Module.fetchSalesData are API call from the PHP
$scope.dtOptions = DTOptionsBuilder
.newOptions()
.withOption('ajax', function (data, callback, settings) {
// set dataSrc
settings.sAjaxDataProp = 'trans';
Module.fetchSalesData({
draw: data.draw,
length: data.length,
start: data.start,
search : data.search.value,
count_again : $scope.countAgain,
startdate: $filter('date')($scope.item.startdate, 'yyyy-MM-dd'),
enddate : $filter('date')($scope.item.enddate, 'yyyy-MM-dd'),
payee_id: $scope.item.payee_id,
staff_id: $scope.item.staff_id,
order: data.order
}).then(function(res) {
$scope.payment_methods = res.data;
callback(res);
$scope.countAgain = false;
})
})
.withOption('serverSide', true)
//This is static dtColumns, User will see this first
$scope.dtColumns = [
DTColumnBuilder.newColumn('invoice_date')
.withTitle('Date')
.withOption('sWidth', '10%'),
DTColumnBuilder.newColumn('ref_num').withTitle('Description')
];
//Set timout waiting server returned **$scope.payment_methods**
//in order to generate dtcolumns dynamically
setTimeout(function() {
angular.forEach($scope.payment_methods, function (value) {
$scope.dtColumns.push(
DTColumnBuilder.newColumn(value).withTitle(value)
.notSortable().withClass('text-right')
.withOption('stateSave', true)
.renderWith(function (data, type, full) {
data = typeof data === 'undefined' ? '0.00' : data;
return $filter('currency')(data, '');
}),
)
});
}, 1000);
Tried
What i have try is using destroy the first table and keep the latest table but it failed
var table = $('#saleReport').DataTable();
table.clear().destroy();
Appreciated of you guys could give me the ideas.
I have two different IDs. One auto increment (using jquery) from an ID called id="H+currentRow+"(+currentRow+ is the current row). And another that does an ajax request to PHP that appends the form with an id="Z#"(# will be depending on the ID in the database).
Ive done this:
$(document).ready(function(){
$("input").change(function(){
var sum=0;
$("[id^=H]").each(function(){
sum=sum+(+parseInt(this.value));
});
var sum2=0;
$("[id^=Z]").each(function(){
sum2=sum2+(+parseInt(this.value));
});
var total = sum + sum2;
if(isNaN(total)) {
var total = 0;
}
$("#total").text(total);
});
});
But thats not working. It works for the first fields but it work for anything else thats being appended. Anyone know whats going on and why its not working?
when you bind an event direct to an element, new elements appended to page will not trigger the event. you have to bind a parent element where inputs are appended to.
Try this bind:
$('body').on('change', 'input', function () {
// your code remain the same here...
});
you can be more specifc than body, binding the event to parent elements of input.
i am trying to add / remove rows dynamically in / from a table using JQuery and the DataTables plugin, at a specific index.
$('#jt').dataTable();
The rows i try to add is some additional info, which i get by clicking on a row (ajax). Each row has a unique id that i pass as an argument.
$('#jt').on('click','.togetinfo',function() {....
$.get(functions, { id: id }).done(function(data) {
....
For each result i add the content to a var and add it after the row i want.
$.each(jsonresult, function(i,item){
subentries = subentries + ....... /* the info */
});
$('#jt > tbody > tr').eq(id).after(subentries);
This works perfectly on the first page, but on the second page of the entries (paging) it does not insert the new data.
The fnAddData() of the "DataTables" API inserts the data on the end of the entire table.
Does anyone has an idea of how to make it work on all the pages?
The false was found in the indexes of each row after the first page.
Each index (on click) must be recalculated.
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
rowIndex = rowIndex - oSettings._iDisplayStart;
I am building scheduling software. I am using a number of tables to display times/dates, etc.
In one particular table there are cells with id's that list the date and employee id number.
I am trying to setup a trading shift system. When the cell is click an ajax function is performed.
Here is an example cell:
<td id="tblcell-2013_03_13-id_3" class="displayShift">$data placed here</td>
Jquery code:
$(document).ready(function () {
// I can't do this because each id is different
$("td#tblcell").click(function () {
alert('it works!');
});
// I can't do this because there other other td elements on the same page in other tables
$("td").click(function () {
alert('it works!');
});
});
How do I set up a function that is activated when a specific cell is clicked that also passess var data to the function in a script that has other td table elements that can't be referenced in this function?
thanks
You can use the td[id^="tblcell"] selector to select all TDs with their ID starting with tblcell
$('td[id^="tblcell"]').click(function() {
// ... do stuff ...
});
Demo for attribute-value-starts-with selector: http://jsfiddle.net/ARkxD/
ok, so I have a database comprising of two tables, products and suppliers.
All suppliers fill in a form and their data is then stored in the suppliers table, and the products table contains a list of all of the products, so when the supplier fills in the form, he can choose as many products as he wishes as I use jQuery JSON and AJAX to get the list of all of the products and then populate a drop down list with all of them in it, which can then be cloned as many times as is needed.
The problem I am sitting with now is, how do I insert all of the different products the supplier chooses into the supplier table, or should I rather just relate all of the products he chooses to the one supplier for better normalization since all the products are already there?
I will be using jQuery $.ajax to POST the form data in JSON format to a waiting PHP file, which will then parse it and insert the data into the database.
So basically, I need to figure out how to relate the data in the database to achieve the best normalization possible, and I need to figure out a way of inserting a variable amount of products into the suppliers table or find a way to relate the many products he chooses to the one supplier.
I am very new to relational databases, so any advice on how to proceed would be a great help, so would any other advice you guys may have!
The jQuery code I use to populate clone and POST the products the supplier chooses:
$(document).ready(function() {
var count = 0;
//when clicked it will remove the closest div with a class of 'container'
$("span.remove").live('click', function(){
$(this).closest("div.container").fadeOut(400, function(){
$(this).remove();
$('#button').attr('disabled','');
});
});
//initialize the button
$('#button').attr('disabled','');
$('#button').click(function(){
var count = $("#systems_wrapper > .container").size();
var lastID = $("#systems_wrapper > .container:last").attr('id');
var exploded = lastID.split("_");
var increment = Number(exploded[1])+1;
//if the user has selected 5 products, disable the 'add' button
if(count >= 5){
$('#button').attr('disabled','disabled');
}else {
$('#button').attr('disabled','');
}
//clone the first drop down and give it a different ID, as well as it's child elements
var test = $('#systems_0.container').clone().attr('id', 'system_' + increment).appendTo('#systems_wrapper');
test.children(':nth-child(2)').append('<span class="remove"></span>');
test.children(':nth-child(2)').children(':first').attr('id', 'mail_' + increment).attr('class','dropDowns').attr('onchange','test();');
});
//get the products JSON object returned from test_post.php and run the necessary functions on the returned data
$.getJSON("test_post.php", function(data){
//clean out the select list
$('#box').html('');
//run the loop to populate the drop down list
$.each(data, function(i, products) {
$('#box').append(
$('<option></option>').html(products.products)
);
});
});
});
//this gets all of the products chosen and then gets each ones value and ID, and then posts it to the qwer.php file
function test(){
var sections = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
sections.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
alert(newArray);
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: JSON.stringify(newArray) }
});
}
Thanx in advance!
If i understand the problem correctly from a database level, should you be using an intermediate table called something like ProductSupplier containing a Product_ID and Supplier_ID column.
Then when a supplier selects a product, add both the supplier and product id to a new column in this table.
This will allow multiple suppliers to pick the same product and multiple products to be picked by the same supplier.
EDIT: I meant to say "add both the supplier and product id to a new ROW in this table"