change table into dataTable - javascript

Some one please guide me on how to change my table as dataTable.
My table will be loaded dynamically using below code.
$.post('geterpitem',{grn : $('#grn').val()}, function(responseJson) {
if(responseJson.length!=null){
var $tbl = $("#itemtable");
$tbody = $tbl.find('tbody');
$tbl.find("tr:gt(0)").remove();
var i = 1;
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).append(i);
rowNew.children().eq(1).text(value['itemcode']);
rowNew.children().eq(2).text(value['itemname']);
rowNew.children().eq(3).text(value['receivedqty']);
rowNew.children().eq(4).html('<input type="text" id="inspdate"/>');
rowNew.children().eq(5).html('<input type="text" id="accqty" onkeypress="return isNumber(event)"/>');
rowNew.children().eq(6).html('<input type="text" id="rejqty" class="reject"/>');
rowNew.children().eq(7).html('<input type="text" id="rema"/>');
rowNew.appendTo($tbody);
i++;
});
}
}
Since I am new to this, Please someone help me to do.

Try something like this
HTML
<table id="searchResultTable" class="display">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="resultscontainer">
</tbody>
</table>
Script
searchResultTable = $("#searchResultTable").dataTable({
"lengthMenu": [20],
"order": [[1, "desc"]],
"ordering": false,
"bFilter": false
});
searchResultTable.on('click', 'tr', DataTableRowClickEventHandler);
searchResultTable.fnClearTable();
for(i=0; i<response.length; i++){
....get values for Col1, Col2, Col3, Col4....
searchResultTable.fnAddData([Col1, Col2, Col3, Col4]);
}
Try below mentioned link for more documentation and examples,
https://datatables.net/examples/ajax/simple.html

Related

How to generate automatically the sum price of a dynamic table using jquery?

I'm making a web-based POS. I have two table, one is for displaying the search products using jquery and when I clicked the product it will transfer to the second table. So my second table is dynamically dependent of what the user clicked. This is my table look like with css.
I want to get the total price of Sub.Total column automatically and display to the bottom specially in the Total p tag.
This is my html table code.
<table id="table2">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
<table id="table1">
<thead>
<tr>
<td>Barcode</td>
<td>Product Name</td>
<td>Price</td>
<td>Unit</td>
<td>Stocks</td>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
This is my query from search box.
$show = "SELECT * FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<tr class='js-add' data-barcode=".$row['id']." data-product=".$row['product_name']." data-price=".$row['sell_price']." data-unt=".$row['unit']."><td>".$row['id']."</td><td>".$row['product_name']."</td>";
echo "<td>₱".$row['sell_price']."</td>";
echo "<td>".$row['unit']."</td>";
echo "<td>".$row['quantity']."</td>";
}
}
This is for displaying the cliked rows from searched products.
$('body').on('click','.js-add',function(){
var target = $(this);
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
swal("Enter number of item to buy:", {
content: "input",
})
.then((value) => {
if (value == "") {
swal("Error","Entered none!","error");
}else{
var qtynum = parseInt(value);
if (isNaN(qtynum)){
swal("Error","Please input a valid number!","error");
}else{
var total = value * price;
$('#tableData').append("<tr><td>"+barcode+"</td
<td>"+product+"</td>
<td>"+accounting.formatMoney(price,{symbol:"₱",format: "%s %v"})+"</td><td>"+unit+"</td>
<td>"+value+"</td>
<td class='totalPrice'>"+accounting.formatMoney(total,{symbol:"₱",format: "%s %v"})+"</td>
<td><button class='btn btn-danger' type='button' id='delete-row'>&times</button><tr>");
}
}
});
});
I'd tried this code but it return NaN.
$(document).ready(function(){
var TotalValue = 0;
$("#tableData tr").each(function(){
TotalValue += parseFloat($(this).find('.totalPrice').text().replace(/,/g, "₱"));
});
alert(TotalValue);
});
I'd tried modifying the code but I cant get the job done. Hope someone will help about this one. Thanks in advance.
Edit: Updated answer.
Based off what you tried here would be a working solution using your logic.
$(document).ready(function(){
var TotalValue = 0;
var TotalPriceArr = $('.totalPrice').get()
$(TotalPriceArr).each(function(){
TotalValue +=parseInt($(this).text().replace('₱', ''))
});
alert(TotalValue);
});

Populate Table Content with Data From Ajax

I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);

How to Get Data from checkbox selected row in dataTables

I'm using this data table.
I need to get both ProductID & ProductStatus from the selected row where ProductID is embedded in the TR ID of each row.
I'm not displaying the productStatus in the table. But I need to get the status when the row is selected. Where can i add them ?
Please Guide me ....
CODE
function loadClick() {
const databaseRef = firebase.database().ref('S01/Products');
var query = databaseRef.orderByKey().startAt("C09M03S03").endAt("C09M03S04").limitToFirst(6);
query.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var t = $('#products_table').DataTable();
var key = childSnapshot.key;
var MID = childSnapshot.child("productMID").val();
var SID = childSnapshot.child("productSID").val();
var ProductID = childSnapshot.child("productID").val();
var name = childSnapshot.child("productName").val();
var unit = childSnapshot.child("productUnit").val();
var productMRP = childSnapshot.child("productMRP").val();
var price = childSnapshot.child("productSellingPrice").val();
var buying_price = childSnapshot.child("productBuyingPrice").val();
var productstatus = childSnapshot.child("productStatus").val();
var row = "";
t.row.add(['<td class="cell-60 responsive-hide"></td><td class="cell-300"><a class="avatar" href="javascript:void(0)"><img class="img-responsive" src="../../../global/portraits/1.jpg"alt="..."></a></td>', '<td>' + name + '</td>',
'<td>' + unit + '</td>', '<td tabindex="1">' + productMRP + '</td>', '<td tabindex="2">' + price + '<\/td>',
'<td tabindex="3">' + buying_price + '<\/td>']).node().id = ProductID;
t.draw(false);
});
});
}
function EditProdStatus(ProductID, ProductStatus) {
var statusRef = firebase.database().ref('S01/Products').child(ProductID).child("productStatus");
statusRef.set(!ProductStatus);
console.log("Product Status changed to " + ProductStatus);
}
$(document).ready(function () {
loadClick();
var table = $('#products_table').DataTable({
'columnDefs': [{
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
'targets': 3,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('tabindex', '1');
}
},
{
'targets': 4,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('tabindex', '2');
}
},
{
'targets': 5,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('tabindex', '3');
}
}
],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
});
function productDisable() {
var oTable = $('#products_table').dataTable();
$(".select-checkbox:checked", oTable.fnGetNodes()).each(function () {
console.log($(this).val());
});
}
HTML
<table id="products_table" class="table is-indent tablesaw" cellspacing="0" width="100%">
<thead>
<tr>
<th class="pre-cell"></th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="3">Product Name</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Product Unit</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Product MRP</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Selling Price</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Buying Price</th>
</tr>
</thead>
</table>
jsFiddle Demo
For those td which you don't want to display in DataTable, you just need to provide Visible:false in your columnDefs. They will be hidden but you can retrieve their data if they are in selected rows.
$('#example').DataTable({
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
}, {
"targets": [2],
"visible": false,
"searchable": false
}]
})
Another thing is you are using fnGetNodes which is a legacy function for datatable v1.9 on selection which is not going to work for DataTable 10.1. You can get selected rows as follow:
table.rows('.selected').data();
This is going to return selected rows even if you have selected multiple rows in different pages.
You can find a Demo here.
As you can see in demo that for Employees data, their position column in not visible in DataTable but its data is available while retrieving data of selected rows.
Documentation here for Hidden columns
Update
I have updated your Fiddle. Updated Fiddle .
Try this, it helps you
var table = $('#example').DataTable();
$('#example tbody').on( 'click', '.checkbox', function () {
if(this.checked==true)
{
console.log( table.row( this.closest('tr') ).data() );
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/js/jquery.dataTables.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/css/jquery.dataTables.css" rel="stylesheet"/>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>check</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox" ></td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" ></td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
</tbody>
</table>
Try this ...
Add your productStatus column to the HTML :
'<td>' + productStatus + '</td>'
Let's say that's at column index 8. So add the following to the dataTables columnDefs :
{
'targets': 8,
'visible': false,
}
Now, in productDisable(), you can get productID & productStatus from each selected row as follows :
function productDisable() {
table.rows(".selected").every(function() {
var row = this.node();
var productID = row.id;
var productStatus = this.data()[8];
console.log(productID, productStatus);
// do whatever with productID and productStatus
});
}
Demo
I a using Datatable 1.10 and this Code is Working for me
"btnSubmit" is the Id of the Button when you click on the button selected checkbox data you will get
// Handle form submission event
$('#btnSubmit').on('click', function() {
//Hold the Object Data what are the checkbox selected
var tblData = table.api().rows('.selected').data();
var tmpData;
//Iterate the Object and extract you one one by one row data With Hidden Id Also
$.each(tblData, function(i, val) {
tmpData = tblData[i];
alert(tmpData);
});
})
//You can use this one.
$( $('#example').DataTable().$('.checked').map(function ()
{
return $(this).closest('tr');
//want to get attribute
//var id = $(this).closest('tr').find('td.Select').attr('id');
}));

generating table with text box

I've a bit of experience coding in php but am fairly new to js. What I'm trying to do in js is create a simple order form, each line is to have a text box indicating the quantity to be ordered, product name and product price, with the latter to be populated from product array prod. My fairly rudimentary first attempt appears below, which needless to say doesn't work.
<body onload="populate()">
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function populate(){
var prod; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i=0; i<prod.length; i++)
{
var newTr = table.insertRow(-1);
var numOrdered=document.createElement('input');
numOrdered.type='text';
numOrdered.id= "product "+i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(num);
newTr.insertCell(-1).appendChild(document.createTextNode(prod["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod["price"]));
}
}
</script>
</body>
Any and all help appreciated.
have a look at the snippet at the bottom.
what's changed is:
in this line you targeted the wrong id, should have been 'demo'
var table = document.getElementById("theTable");
you also needed to reference the correct value in your array inside the loop:
document.createTextNode(prod["name"]);
to:
document.createTextNode(prod[i]["name"]);
and lastly this line:
newTr.insertCell(0).appendChild(num);
to:
newTr.insertCell(0).appendChild(numOrdered);
hope this helps.
function populate() {
var prod = [{
name: 'box',
price: 20
}, {
name: 'plane',
price: 40
}]; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i = 0; i < prod.length; i++) {
var newTr = table.insertRow(-1);
var numOrdered = document.createElement('input');
numOrdered.type = 'text';
numOrdered.id = "product " + i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(numOrdered);
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["price"]));
}
}
populate();
<table id="theTable">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try This code:
I am using jQuery, to create, append and iterating the array(each Loop).It is a better and effective way. Please use jQuery for DOM manipulation.
HTML:
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS:
table,td{display:block}
th{width:100px}
td{margin:10px}
JS:
var prod=[{product:'samsung',price:100},{product:'apple',price:200},{product:'micromax',price:300}];
(function($){
$.each(prod,function(index,value){
$('#demo th:eq(0)').append("<td><input type='text'></td>");
$('#demo th:eq(1)').append("<td>"+value.product.toUpperCase()+"</td>");
$('#demo th:eq(2)').append("<td>"+value.price+"</td>")
});
})(jQuery);
Here is the JSFiddle Link:
https://jsfiddle.net/Dee0565/8vww1pwf/

create json object from html table using selected colums using jquery

i was wondering how to parse html table to get json object that i can send via $.post with jquery.
i have a table
<table id="Report">
<thead>
<tr>
<th>Kod</th>
<th>Nazwa</th>
<th>Ilość</th>
<th>Netto / 1szt.</th>
<th>Suma brutto</th>
</tr>
</thead>
<tbody>
<tr>
<td>00171 </td>
<td>SŁUP 50/1800 POŚREDNI(P) </td>
<td>5</td><td>97.00 PLN </td>
<td>394.31 PLN </td>
</tr>
<tr>
<td>00172</td>
<td>SŁUP 50/1800 NAROŻNY(P)</td>
<td>1</td><td>97.00 PLN</td>
<td>78.86 PLN</td>
</tr>
<tr>
<td>00173 </td>
<td>SŁUP 50/1800 KOŃCOWY(P) </td>
<td>1</td><td>97.00 PLN </td>
<td>78.86 PLN</td>
</tr>
</tbody>
<tfoot style="font-weight: bold;">
<tr>
<th colspan="3" style="text-align: right;">Razem netto: 1955.85 PLN</th>
<th colspan="2" style="text-align: right;">Razem brutto: 2405.69 PLN</th>
</tr>
</tfoot>
</table>
and what i need is json object in this format (first <td> and third <td>):
[{"00171":5},
{"00172":1},
{"00173":1}
]
and that i can send it via
$.post(
"print.php",
{json: myjsonvar},
"json"
);
any idea how to do that?
thanks
var json = [];
$('#Report').find('tbody tr').each(function(){
var obj = {},
$td = $(this).find('td'),
key = $td.eq(0).text(),
val = parseInt( $td.eq(2).text(), 10 );
obj[key] = val;
json.push(obj);
});
How about:
var myjsonvar=[];
$('#Report tbody tr').each(function(){
var data={};
var tr=$(this);
data[tr.find('td:first-child').text()]=tr.find('td:nth-child(3)').text();
myjsonvar.push(data);
});
var sendData = [];
$('#Report tbody tr').each(function(i, el){
var key = $.trim($(this).find('td:eq(0)').text()),
val = $.trim($(this).find('td:eq(2)').text()),
obj = {};
obj[key] = val;
sendData.push(obj);
});
See demo
Why json, if you are in js already? Just create a simple object:
var data = {};
$("#Report tbody tr").each(function() {
data[$(this).children("td:eq(0)").text()] = $(this).children("td:eq(2)").text();
});
$.post("print.php", data);
Setting type to json in $.post defines the server response to be json, not the send data!
http://jsfiddle.net/zyCPN/
var objArray=[];
$('table#Report tbody tr').each(function(i){
var row=$(this);
obj={};
obj[$('td', row).eq(0).text()]=$('td', row).eq(2).text();
objArray.push(obj);
});

Categories