I'm currently trying to fill dynamically a table with content retrieved from a JSON Object.
Here is the table:
<table id="datatable_tabletools" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th data-hide="phone">ID</th>
<th data-class="expand">Nom</th>
<th data-hide="phone">Commentaires</th>
<th data-hide="phone,tablet">Date</th>
<th data-hide="phone,tablet">Attachements</th>
<th data-hide="phone,tablet">Actions</th>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
I have multiple interesting features in the table such as a search option, a filter, sort, export as PDF, etc,....those features are working properly if I'm including static content such as:
<tr>
<td>33</td>
<td>Bevis</td>
<td>1-955-717-0835</td>
<td>Est Ac Inc.</td>
<td>7424</td>
<td>Ichtegem</td>
</tr>
but as soon as I retrieve data table content from My JSON object, I'm not able to use those features anymore, sort doesn't work, search neither.
Here is the JavaScript I'm using:
$(document).ready(function() {
$.get('getAllDocuments', function(responseJson) {
if (responseJson != null) {
var table1 = $("#table");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['id']);
rowNew.children().eq(1).text(value['nom']);
rowNew.children().eq(2).text(value['commentaire']);
rowNew.children().eq(3).text(value['date']);
rowNew.children().eq(4).text(value['id']);
rowNew.children().eq(5).html("Voir Supprimer");
rowNew.appendTo(table1);
});
}
});
});
My table is filled correctly, but not all the functions associated. any idea on how I can fill my table with JSON content in a proper way?
I think you can use ajax option of DataTables like:
var table = $('#example').DataTable( {
ajax: 'data.json'
});
P.S. here is the documentation
Related
I've a separate javascript code which is fetching data from api and inserting in browsers localStorage.
API is fetching ETA data and saving in localStorage as id_ETA(e.g 12342_ETA) key.
When the values in local storage gets updated then my html table ETA column values should also get updated without refreshing the page.
Right now I need to refresh the entire page in order to view the updated ETA in the html.
HTML Table:
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Arrival Address</th>
<th>Departure Address</th>
<th>ETA</th>
</tr>
</thead>
<tbody>
<script>
var data = getPlanData();
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Arrival Address</th>
<th>Departure Address</th>
<th>ETA</th>
</tr>
</thead>
<tbody>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['id']+"</td>");
document.write("<td>"+data[i]['arrival']+"</td>");
document.write("<td>"+data[i]['departure']+"</td>");
document.write("<td>"+data[i]['arrival']+"</td>");
if (localStorage.getItem(data[i]['id']+'_ETA'))
{
document.write("<td>"+localStorage.getItem(data[i]['id']+'_ETA')+"</td>");
}
else
{
document.write("<td>-</td>");
}
document.write("</tr>");
</script>
</tbody>
</table>
</div>
getPlanData():
function getPlanData() {
localData = localStorage.getItem('plan');
result = csvToJSON(localData);
return result;
}
Note: ETA is coming from separate API
Is there a way to update the ETA column when there is new ETA value in localStorage without refreshing the page?
Assuming getPlanData() does the writing to localStorage, you need to do two things
Don't use document.write, certainly not after load since it wipes the page
save to localStorage in getPlanData() AND
call this update with the data in the getPlanData function - this script can be copied to the head of the document inside script tags and called as update(data)
const update = data => {
const html = data.map(item => (
`<tr>
<td>${item.id}</td>
<td>${item.arrival}</td>
<td>${item.departure}</td>
<td>${item.arrival}</td>
<td>${localStorage.getItem(item.id+"_ETA") || "-"}</td>
</tr>`));
document.querySelector(".table tbody").innerHTML=html.join("")
}
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Arrival Address</th>
<th>Departure Address</th>
<th>ETA</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
If you post an example of your data, I am sure we can find a better way to get the ETA than localStorage.getItem(item.id+"_ETA")
UPDATE: You CAN do
var data = getPlanData();
update(data)
I am using datatables to display table data. this table has an action column to remove record. I am trying the achieve the delete action by adding the event listener to the specific class. When i am trying to get the elements by the class name it is returning only first page elements of the datatable event though we have 5 pages. Can you help me in this regard.
var lastName = document.querySelectorAll('.lastname');
console.log(lastName);
i need the solution in plain javascript.
<table id="example" class="display nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td><button class="btn btn-primary lastname" name="delete"></td>
</tr>
</table>
<script>
$(document).ready(function() {
$('#example').DataTable(
);
var lastName = document.querySelectorAll('.lastname');
console.log(lastName);// i am expecting this should return all elements with class **lastname**.
});
</script>
I have only included one row. assume we have 50 rows.
you can include the element like div
try this.
var lastName = document.querySelectorAll('div.lastname');
console.log(lastName);
you can read this Documentation for better information.
So i got this table
<table id="table" class="table table-bordered table-hover">
<thead>
<tr>
<th data-field="id" class="hidden">ID</th>
<th data-field="variant">Variant</th>
<th data-field="description">Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
it will be filled with data trough
$('#table').bootstrapTable({
data: returnValue
});
then i can click the rows which will add the class .bg-info to it and i want to check if a row has the class and then save the row data in a var
this was my attempt:
var item = $.map(table.rows('.bg-info').data(), function (item) {
return item[0]
});
but table.rows can't be used as a method apparently
If you want to select all the rows with the class bg-info in your table. Use a jQuery selector based on that class :
var bgInfoRows = $("#table tbody .bg-info");
You will have every item in tbody that has the class bg-info.
Lets say, I have simple datatable
<table datatable="" dt-options="dtOptions" dt-column-defs="dtColumnDefs" class="row-border hover">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr ng-repeat"reservation in reservations">
<td>{{reservation.ID}}</td><td>{{reservation.name}}</td>
</tr>
</tbody>
</table>
When I put some string into search box datatable is being filtered. Now I want to iterate in Angular over filtered rows and read IDs to array. How to deal with it in Angular? I can use jquery but I do not want make a mess in code.
$scope.addressDTInstance = {};
var j = $scope.addressDTInstance.DataTable.rows();
<table id="addressSelectionTable" class="table table-condensed table-bordered" datatable="ng" dt-options="addressdtOptions" dt-column-defs="addressdtColumnDefs" dt-instance="addressDTInstance">
This is something to get you on your way. Need an instance of dtInstance which you don't have. So add dt-instance='dtInstance' in the html table tag.
Then initiate it at the top of your controller, $scope.dtInstance = {};.
Perform a click or some action in your javascript that you can set a break point on and then examine your $scope.dtInstance to see what all properties and methods you have. As you see in my snippet I'm accessing DataTable.Rows of my dtInstance. If you need better example or help let leave me a comment and I'll revise.
UPDATE
Here is a method I found that works. I am ofcourse using the DTOptionsbuilder. This will get called twice, first when it is created and second when i populated the array variable that is populating my table. I just check to see if rows exist and that the first one isn't 'No results'.
$scope.addressdtOptions = DTOptionsBuilder.newOptions()
.withOption('bFilter', false)
.withOption('bInfo', false)
.withOption('paging', false)
.withOption('processing', true)
.withOption('aaSorting', [1, 'asc'])
.withOption('language', { zeroRecords: 'No results' })
.withOption('initComplete', function () {
var rows = $("#addressSelectionTable > tbody > tr");
if (rows.length > 0 && rows[0].innerText !== "No results") {
var x = 3;
}
});
Here i am setting that variable that is ng-repeat for table. You may not be doing it my way, but you should be able to figure it out for your way.
$.when($OfficerService.GetAddressSelections($scope.officer.EntityID, $scope.officer.EntityTypeID, $scope.officer.MemberID)).then(function (result) {
$scope.addresses = result.data;
$scope.$applyAsync();
});
<table id="addressSelectionTable" class="table table-condensed table-bordered" datatable="ng" dt-options="addressdtOptions" dt-column-defs="addressdtColumnDefs" dt-instance="addressDTInstance">
<thead>
<tr>
<th></th>
<th>Type</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Country</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="a in addresses">
<td class="centerColumn">
<input type="button" class="btn btn-primary" value="Select" ng-click="selectAddress(a.AddressID,a.AddressLocationCode,$event)" />
</td>
<td>
<span ng-if="a.AddressLocationCode == 'E'">Office</span>
<span ng-if="a.AddressLocationCode == 'M'">Member</span>
</td>
<td>
{{a.AddressLine1}}
<span ng-if="a.AddressLine2 != null"><br /> {{a.AddressLine2}}</span>
</td>
<td>{{a.City}}</td>
<td>{{a.StateCode}}</td>
<td>{{a.Zip}}</td>
<td>{{a.CountryCode}}</td>
<td>{{a.AddressID}}</td>
</tr>
</tbody>
</table>
For me it works: $scope.dtInstance.DataTable.rows( { search: 'applied' } ).data()
I am using an open source javascript table sorting function on my html table, but it only works if I don't alter the table with another javascript function (which I need to do).
My table:
<table id="myTable" class="random">
<thead>
<tr>
<th>First</th>
<th>Last</th>
</tr>
</thead>
<tbody id ="mybody">
<tr>
<td>James</td>
<td>Smith</td>
</tr>
<tr>
<td>Kyle</td>
<td>Thompson</td>
</tr>
</tbody>
</table>
I also have a function which replaces the rows in the table
function addRow(item, i, tdcount) {
document.getElementById("mybody").innerHTML = //replace rows
}
The sort only works if I don't click the button to replace rows. As soon as I replace rows, the sort stops working. Is there a way to sort a table after it has been altered?
EDIT:
BTW, the table data is generated by an AJAX call to a different server which queries a database and returns a JSON object which I fill into the table
The solution was to simply add a call to the function after the table is altered:
function addRow(item, i, tdcount) {
document.getElementById("mybody").innerHTML = //replace rows
$(document).ready(function () {
$("#myTable").tablesorter();
}
}