How to get information from datatable - javascript - MVC - javascript

I have created an ASP.net MVC app and I have created a DataTable [DataTable.net] as follows:
<table id="invoiceTable">
<thead>
<tr>
<th>Invoice ID</th>
<th>Date</th>
<th>Reciept Date</th>
<th>Category</th>
<th>Total Value</th>
<th>Invoice Ref</th>
<th>Client</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#{
foreach (FreeAgentApp.Models.CustomInvoice _invoice in ViewBag.Invoices)
{
<tr>
<td>#_invoice.InvoiceId</td>
<td>#_invoice.Date</td>
<td>#_invoice.RecpDate</td>
<td>#_invoice.Category</td>
<td>#_invoice.TotalValue</td>
<td>#_invoice.InvoiceRef</td>
<td>#_invoice.Client</td>
<td>#_invoice.Status</td>
</tr>
}
}
</tbody>
</table>
And i can get the information from a row when its selected using javascript as follows:
// Row data
$(document).ready(function () {
oTable = $('#invoiceTable').dataTable();
oTable.$('tr').click(function () {
var data = oTable.fnGetData(this);
alert(data);
// ... do something with the array / object of data for the row
});
});
The variable data will provide a string of every value in the row separated by a comma as follows:
"000,26-01-14,27-01-14,001,1000,inv,something ltd,paid"
I want to have all these values separated. Note this could be done by splitting on the comma however a value in the table could contain commas.
How can I separate this string?

According to the DataTables documentation oTable.fnGetData(this); return an array filled with the data of the definitions in the row so you should be able to acces the data directly from data.
var invoiceId = data[0];
var date = data[1];
var recpDate = data[2];
// etc. etc.

Related

Permanently reverse the order of a DataTable in jQuery?

Let's say I have a Data Table like so:
<table id="history" class="display">
<thead>
<th>Player</th>
<th>Word</th>
<th>Value</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
I have a function that receives a payload from the server and adds a row to the datatable with the relevant information
var history_data_table = $('#history').DataTable({
"pageLength": 5,
"searching": false,
"bLengthChange": false,
"language": {
"emptyTable": "Words that you discover will appear here."
}
});
function liveRecv(word_payload) {
history_data_table.row.add([word_payload.id_in_group,
word_payload.word,
word_payload.word_value,
word_payload.message]
).draw();
Naturally, this will add the row to the end of a paginated table. This table is a list of transactions in a game, and I want to present the most recent transactions to the user, such that every row that's added is added to the top of the data-table. What is the easiest way to achieve this?
You could try this method using jQuery
$('#history tr:first').after("<tr role="row"><td></td><td>add you own row</td></tr>");
or you could use DataTables inner function to access the array of rows
var history_data_table = $('#history').dataTable();
var DisplayMaster = history_data_table.fnSettings()['aiDisplayMaster'];
var tableapi = history_data_table.api();
var getlastrow = DisplayMaster.pop();
DisplayMaster.unshift(getlastrow);
tableapi.draw(false);

how to loop a nested array object in javascript with jquery

Hey im working on a project and i can't seem to get the hang of this. I want to loop through my nested array object "products" so that i can display it all and not just the last index.
// jquery getting our json order data from firebase
$.get("http://localhost:8888/orderslist", (data) => {
// i is for the index of the array of orders
let i = 0;
//for each loop through our array list
$.each(data, function () {
//console.log(data)
//console.log(i);
// is how we arrange the data and show it to the frontpage
$(`<table id = order_table_layout>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
<tr>
<td>${data[i].customer_name}</td>
<td>${data[i].date}</td>
<td>${data[i].time}</td>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
</td>
<td>
</td>
</tr>
</table>`
).appendTo("#frontpage_new_ordertable");
// counts 1 up for each loop to go through list
i++;
//console.log(i);
});
});
Edit:
An example of the json data I'm working with look like this:
[
{
id: "4WQITi6aXvQJsKilBMns",
customer_name: "Susanne",
date: "22-12-2002",
time: "12:43:19",
total: 222,
products: [
{ name: "product name", price: 100 },
{ name: "product name2", price: 20 }
]
There's a couple of issues in your code. Firstly you're creating a brand new table for every object in the data array. It makes far more sense to instead create a new row in the table for each item.
Also, it appears that you want to loop through the child products array. As such you need an inner loop to create the HTML string for those elements outside of the template literal.
However it's worth noting that it's not good practice to have that much HTML in your JS. A better approach is to have a hidden template tr in your HTML which you can clone, update with the data from the data array, then append to the DOM in the tbody of the table.
With that said, try this:
//$.get("http://localhost:8888/orderslist", (data) => {
// mock response:
let data = [{id:"4WQITi6aXvQJsKilBMns",customer_name:"Susanne",date:"22-12-2002",time:"12:43:19",total:222,products:[{name:"product name",price:100},{name:"product name2",price:20}]},{id:"asjdkjk21ijjjew",customer_name:"Foo Bar",date:"10-05-2020",time:"16:46:16",total:68,products:[{name:"Lorem ipsum",price:50},{name:"Fizz buzz",price:18}]}];
let rows = data.map(item => {
let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
$clone.find('.customer-name').text(item.customer_name);
$clone.find('.date').text(item.date);
$clone.find('.time').text(item.time);
$clone.find('.total').text(item.total + ' Kr.');
let products = item.products.map(prod => `${prod.name}: ${prod.price} Kr.`);
$clone.find('.products').html(products.join('<br />'));
return $clone;
});
$("#frontpage_new_ordertable tbody").append(rows);
//});
tfoot {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="frontpage_new_ordertable">
<tbody>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
</tbody>
<tfoot>
<tr>
<td class="customer-name"></td>
<td class="date"></td>
<td class="time"></td>
<td class="total"></td>
<td class="products"></td>
<td></td>
</tr>
</tfoot>
</table>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
maybe that's what's wrong?
is the number of the order similar to the number of product in products array?

Angularjs : ngRepeat list down all the data from server

I successfully fetch data by using $http get from php server. But I have no idea how to display the data in Table form by using ngRepear because all the data is in few different project. I am going to display all the object of data into different row of a table. The following shows data I got from php server.
Following glimpse of code can give you idea
$scope.retrievedData = [];
//retrieve data from your server
//take the data into above scope variable
<table>
<tr ng-repeat = "data in retrievedData">
<td>data.AssetDescription</td>
<td>data.AssetNumber</td>
<td>data.ComputerName</td>
</tr>
</table>
You need to add that data to controller variable:
Controller
function YourController($scope, $http) {
$scope.tableData = [];
$http.get('url').then(function(result) {
$scope.tableData = result.data;
});
}
Template
<table>
<thead>
<tr>
<th>Description</th>
<th>Computer name</th>
<th>Borrow date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in tableData ">
<td>{{row.data.AssetDescription}}</td>
<td>{{row.data.ComputerName}}</td>
<td>{{row.data.borrowDate}}</td>
</tr>
</tbody>
</table>

How to display dynamically added form elements in a table in a different webpage when the data is saved in local storage using purely javascript?

I'm doing a school project in which I'm creating webpages to allow users to input and then display it on another page. I am only using javascript, html and css for the webpages.
On the Create An Event page is a form. I have saved all the input into local storage but now I am unsure on how to retrieve the data to display in on another page called Event History. Here are my codes:
function saveToStorage() {
var nameofevent=document.getElementById("name").value;
var pList=document.getElementsByName("pos");
var positions=[];
for (i=0; i<pList.length; i++){
positions.push(pList[i].value);
console.log(pList[i].value);
}
//for (i=0; i<positions.length; i++){
//console.log(positions[i].value);
//}
var venue= document.getElementById("venue").value;
var date=document.getElementById("date").value;
var starttime=document.getElementById("timeStart").value;
var endtime=document.getElementById("timeEnd").value;
var contact=document.getElementById("contact").value;
var email=document.getElementById("email").value;
var desc=document.getElementById("desc").value;
var one={"name":nameofevent,"pos":positions,"venue":venue,"date":date,"timeStart":starttime,"timeEnd":endtime,"contact":contact,"email":email,"desc":desc};
localStorage["CreateEvent"]=JSON.stringify(one);
return false;
}
Whenever the user submits the Create An Event form, the data that the user inputs will be displayed in a table in another page. Here are my codes for the table:
<h1>Events Created</h1>
<table border="1px" id="tab">
<thead>
<tr style=" font-size: 30px">
<th id="event">Name of event</th>
<th>Positions</th>
<th id="">Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>eg. Name</td>
<td>eg. Position1, position2</td>
<td>eg. venue</td>
<td>eg. date</td>
<td>eg. start time</td>
<td>eg. end time</td>
</tr>
</tbody>
var saved=JSON.parse(localStorage.getItem("createEvent"));
alert(saved.name);
//etc
You can simply read from the localStorage in the same way, you wrote to it.
You could add this function to your js:
function loadEvents() {
//get the JSON Object from local storage
var event = JSON.parse(localStorage["CreateEvent"]);
//get the first row in the table
var firstRow = document.querySelector('table tbody tr');
//get the single tds
var eventName = firstRow.querySelector('td:nth-child(1)');
//put the data into the tds
eventName.innerHTML = event.name;
}
Call this function with <body onLoad="loadEvents()"in your View Events page.
Make sure you add the <script /> to the file.
This way it is very cumbersome to select the child nodes, so maybe you would want to put some classes in your markup.

JQuery tablesorter appended data not sorting

Im trying too append data to a table with the tablesorter plugin (http://tablesorter.com)
Im using the following code:
<table id="sortme" border="1" style="width: 200px;">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td>will</td>
<td>smith</td>
<td>1</td>
</tr>
...................
</tbody>
</table>
Click me!
And:
$(document).ready(function() {
var i = 5;
$("#sortme").tablesorter({
sortList: [[2,0]]
});
$("#test").click(function() {
$("#sortme tbody").append('<tr><td>NEW</td><td>NEW</td><td>'+(i++)+'</td></tr>');
$("#sortme").trigger("update");
var s = [[2,0]];
$("#sortme").trigger("sorton",[s]);
return false;
});
});
Problem is the appended row stays at top, why?
See example: http://jsfiddle.net/jmU3Z/8/
In case anyone else stumbles across this.
By the time the "sorton" event is handled the DOM hasn't been assigned the table.config.parsers. The "sorton" event handling needs to be wrapped in a 1 millisecond timeout.
Replace the existing "sorton" bind in jquery.tablesorter.js (line ~803) with the following:
}).bind("sorton", function (e, list) {
var me = this;
setTimeout(function () {
$(this).trigger("sortStart");
config.sortList = list;
// update and store the sortlist
var sortList = config.sortList;
// update header count index
updateHeaderSortCount(me, sortList);
// set css for headers
setHeadersCss(me, $headers, sortList, sortCSS);
// sort the table and append it to the dom
appendToTable(me, multisort(me, sortList, cache));
}, 1);
You're problem is the [s]. You're sort parameter is already an array, just pass it the var not the var in an array.
$("#sortme").trigger("sorton",s);
Works for me, FF4.

Categories

Resources