LocalStorage : Row Table not display when page reloaded - javascript

Good Morning.
I already store table into localStorage.
but when im reload the page, The Row in the Default Table not displaying.
and if i'm disable initialization it's will be working fine,
but not when i'm Add new table, The Default Table will not displayed when page reloaded :
// Defaul Table
$("#mainTable").dataTable({
"ajax": "https://api.myjson.com/bins/1hes6z",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
});
/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
function getTableList() {
var addTable = '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
'<div class="zf-table">' +
'<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade dynamicTable">' +
'<thead>' +
'<tr>' +
'<th style="border-color:rgb(221, 221, 221);"> </th>' +
'<th>Audience Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'<th>Action</th>' +
'</tr>' +
'</thead><tbody></tbody>' +
'</table>' +
'</div>' +
'</div>';
return addTable;
}
if (true) {
/** INDEX FOR INCREMENT ID **/
if (typeof(Storage) !== "undefined") {
if (localStorage.Index) {
localStorage.Index = Number(localStorage.Index) + 1;
} else {
localStorage.Index = 1;
}
} // if storage
var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable == null) {
resultTable = [];
}
let newtableHTML = getTableList();
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
/* append Table baru */
$('.tab-content').append(newtableHTML);
var newTable = $("#table" + localStorage.Index).dataTable();
alert("sucess create table");
} else {
alert("Failed create Table");
}
}); // submitButton func
//on init fill the table-content
$(document).ready(function() {
$("#mainTable").dataTable();
var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {
//get the nav reference in DOM
let tableContent = $(".tab-content");
//clear the html contents
tableContent.html('');
for (var i = 0; i < resultTable.length; i++) {
var items = resultTable[i];
$(".tab-content").append(items.table);
}
$(".dynamicTable").dataTable();
} else {
let inititalTable = [];
inititalTable.push({
table: $('div.tab-content').html()
});
localStorage.setItem("tableList", JSON.stringify(inititalTable));
}
});
How to display the row table when page reloaded without deleting initialTable code?
JSFiddle Demo

Related

How to append table row inside parent table after selecting dropdown list using JavaScript and Ajax?

I am creating a table using Ajax and JavaScript and using Spring Boot as a backend technology. So the scenario is:
There are two dropdowns one for selecting company name from list and with that company, corresponding truck list would be displayed. After selecting company name and truck from both the dropdowns, clicking on search button there would display a table with dynamic data of selected company and truck. So, for each created row there is select drop down in table row. So I want to display further data when selecting any of the option list from dropdown.
I want to display child row inside parent row after selecting any of the option from dropdown list using Ajax and JavaScript.
Below is my script where I am creating table with dynamic data:
function searchdata(){
var companyid = $("#searchQueryDD").val();
var truckid = $("#searchtruckdd").val();
var url = "api/gettablebycompanyandtruck";
$.post(url, {
companyid : companyid,
truckid : truckid,
limit : limit,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var row = "", tripnumber="";
var newtrip = [];
var uniquetrip = {};
var row = "";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
tripnumber = list[i].tripnumber;
uniquetrip[tripnumber] = list[i];
}
for(var i in uniquetrip){
newtrip.push(uniquetrip[i]);
}
for(var i = 0; i < newtrip.length; i++){
row = row + "<tr>" +
"<td>"+newtrip[i].company.companyname+"</td>" +
"<td>"+newtrip[i].driver.username+"</td>" +
"<td>"+newtrip[i].truck.name+"</td>" +
"<td>"+newtrip[i].tripnumber+"</td>" +
"<input type='hidden' id='company_id' value='"+newtrip[i].company.companyid+"'>" +
"<input type='hidden' id='trip_number' value='"+newtrip[i].tripnumber+"'>"+
"<td><select onchange='getmorerows();' id='sub_trip'>" +
"<option selected disabled>Choose subtrip</option><option value='1'>1</option>" +
"<option value='2'>2</option><option value='3'>3</option></select></td>"+
"<td>"+newtrip[i].pickupdate+"</td>" +
"<td>"+newtrip[i].deliverydate+"</td>"+
"<td>"+newtrip[i].loadrate+"</td>" +
"<td>"+newtrip[i].dispatchfee+"</td>" +
"<td>"+newtrip[i].fuel+"</td>" +
"<td>"+newtrip[i].cardfee+"</td>" +
"<td>"+newtrip[i].onroadrepair+"</td>" +
"<td>"+newtrip[i].shoprepair+"</td>" +
"<td>"+newtrip[i].trailerrent+"</td>" +
"<td>"+newtrip[i].comcheck+"</td>" +
"<td>"+newtrip[i].advance+"</td>" +
"<td>"+newtrip[i].miscellenous+"</td>" +
"<td>"+newtrip[i].total+"</td>" +
"<td>"+newtrip[i].layover+"</td>" +
"<td>"+newtrip[i].grandtotal+"</td>" +
"<td>" +
"<a data-toggle='modal' data-target='#mode_payment' onclick=\"getpayment('"+newtrip[i].tripid+"');\">"
+"<i class='fa fa-paypal' aria-hidden='true' style='color:#3585a5'></i>" +
"</a>" +
"<a onclick=\"getTrip('"+newtrip[i].tripid+"');\">"
+"<i class='fa fa-pencil-square-o ml-3' style='color: #3384a4;'></i>" +
"</a>" +
"<a href='invoice?id="+newtrip[i].tripid+"'>"
+"<i class='fa fa-file-pdf-o ml-3' aria-hidden='true' style='color:red'></i>" +
"</a>" +
"</td>" +
"</tr>";
}
}else{
row = row + "<tr><td colspan='19' style='font-size: initial;font-family: initial;'>No Data Available.</td></tr>";
}
document.getElementById('searchresulttable').innerHTML = row;
$("#triptable").css('display','inline-block');
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
And below script is to handle onchange event on select options:
function getmorerows() {
var companyid = document.getElementById("company_id").value;
var tripnumber = document.getElementById("trip_number").value;
var subtrip = document.getElementById("sub_trip").value;
var url = "api/getbysubtrip";
$.post(url,{
companyid : companyid,
tripnumber : tripnumber,
subtrip : subtrip,
},function(data, status){
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var childrow = "";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
childrow = childrow + "<tr class='display-nonee'>" +
"<td>"+list[i].company.companyname+"</td>"+
"<td>"+list[i].company.companyname+"</td>"+
"<td>"+list[i].company.companyname+"</td>"+
"</tr>";
var tr = $(this).parent().parent().nextAll(':lt(2)');
if (tr.is(".display-none")) {
tr.removeClass('display-none');
} else {
tr.addClass('display-none');
}
}
}
document.getElementById('searchresulttable').innerHTML = childrow;
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
Change one line in getmorerows()
document.getElementById('searchresulttable').innerHTML = childrow; to $('#searchresulttable').append(childrow);

build unique table with JQuery AJAX

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

datatable append html but got refreshed?

Not sure what is wrong, for me my code has the right logic. But somehow the html didn't stay after 2nd click onward. I expect my custom html would appear after the newly added tr.
my function
function appendRow(name, position, office, age, date,salary) {
var t = $('#example').DataTable();
var node = t.row.add([
name,
position,
office,
age,
date,
salary,
]).draw().node();
var detail_row = '';
detail_row = '<h3>Custom HTML</h3>';
$(node).addClass('result-row');
node = node.outerHTML += detail_row;
$(node).hide().fadeIn('normal');
}
https://jsfiddle.net/282w8yfk/
it is happening in this way because you applied sorting on the name column, so datatable being quite smart it adds the row where it needs to be... so if you want to add that in the last remove sorting option on name column...
and here is a small code change:
$(document).ready(function() {
/* Formatting function for row details - modify as you need */
function format(d) {
console.log(d);
// `d` is the original data object for the row
return '<table cellpadding="4" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Name:</td>' +
'<td>' + d[0] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Full Name:</td>' +
'<td>' + d[4] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Extra info:</td>' +
'<td>And any further details here (images etc)...</td>' +
'</tr>' +
'</table>';
}
var table = $('#example').DataTable({
"columnDefs": [{
"targets": [4],
"visible": false,
"searchable": false
}]
/* the problem is here, it won't work if I enable sorting*/
});
function appendRow() {
var t = $('#example').DataTable();
var node = t.row.add([
"James Bond",
"Spy", "55", "$9000", "James Bond Larry"
]).draw().node();
console.log(node);
$(node).addClass('result-row').hide().fadeIn('normal');
};
$('#add').click(function() {
appendRow();
});
$('#example tbody').on('click', '.result-row', function() {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
});
reference 1 - sort
reference 2 - row.add

Update totals in a table

I have:
$('#createStockOrder').click(function () {
modal('create-stock-order', {}, function () {
var $modal = $(this);
var submitted = false;
var model = [];
$('.glyphicon-plus').click(function () {
var product_id = $('#productSelect option:selected').text(),
size_id = $('#sizeSelect option:selected').text(),
colour_id = $('#colourSelect option:selected').text(),
quantity = $('#quantity').val();
// Get index of the element where all the fields matches
var index = getObjectIndex(model, product_id, size_id, colour_id);
// If object found in the array
if (index !== false) {
// Update the quantity in the same element
model[index].quantity = quantity;
} else {
// Add the element in the array
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
}
printStock(model);
});
var form = document.getElementById('create_sale');
var $form = $(form);
$form.on('submit', function (e) {
e.preventDefault();
if (!submitted) {
submitted = true;
$('#create_sale .btn-primary').addClass('disabled');
var formData = new FormData(form);
qwest.post(form.action, formData)
.then(function (resp) {
$modal.modal('hide');
})
.catch(function (xhr, response, e) {
var html = '';
$.each(response, function (i, v) {
html += '<p>' + v + '</p>';
});
$('#create_sale .alert').html(html).removeClass('hide');
$('#create_sale .btn-primary').removeClass('disabled');
submitted = false;
});
}
})
}, {width: 1000});
});
// Currently the function is Static, but it can be changed to dynamic
// by using nested loop and a flag to store the match status
function getObjectIndex(arr, product_id, size_id, colour_id) {
// Loop over array to find the matching element/object
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
if (obj.product_id === product_id && obj.size_id === size_id && obj.colour_id === colour_id) {
// When all key-value matches return the array index
return i;
}
}
// When no match found, return false
return false;
}
function printStock(model) {
var html = '';
var total_row_quantity = 0;
var total_row_value = 0;
$.each(model, function (i1, v1) {
html += '<tr>';
$.each(v1, function (i2, v2) {
html += '<td>' + v2 + '</td>';
$('#product_totals tr').each(function(i3, v3){
var product_code = $('td', v3).eq(0).html();
if(product_code == v2) {
total_row_quantity += parseInt(model[i1].quantity);
total_row_value += parseFloat($('td', v3).eq(2).html()*model[i1].quantity);
$('td', v3).eq(1).html(total_row_quantity);
$('td', v3).eq(3).html(accounting.formatMoney(total_row_value, ''));
} else {
total_row_quantity = 0;
total_row_value = 0;
}
})
});
html += '</tr>';
});
$('#stock_order tbody').html(html);
}
The HTML is:
<tbody id="product_totals">
<tr data-id="1">
<td>JW1501</td>
<td class="code-quantity-total">0</td>
<td>79.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="2">
<td>JW1502</td>
<td class="code-quantity-total">0</td>
<td>99.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="3">
<td>JW1501-1</td>
<td class="code-quantity-total">0</td>
<td>20.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="4">
<td>JW1502-2</td>
<td class="code-quantity-total">0</td>
<td>25.00</td>
<td class="code-cost-total">0</td>
</tr>
</tbody>
The list of rows (JW1501, JW1502) is dynamic.
The problem I am having is that if a variant of e.g. JW1502 is added, only the total quantity and value is calculated for that one. Any previous different variants of JW1502 are ignored.
How can I fix this?
Example content of var model:
[
{"product_id":"JW1501","size_id":"70A","colour_id":"小豹纹","quantity":"1"},
{"product_id":"JW1501","size_id":"75B","colour_id":"小豹纹","quantity":"2"},
{"product_id":"JW1502","size_id":"85A","colour_id":"黑色","quantity":"1"}
]
The above for JW1501 would show the incorrect quantity of 2, not 3.
...
$('#product_totals tr').each(function (i3, v3) {
console.log(v1, v2, v3)
...
Outputs:
Object {product_id: "JW1501", size_id: "70A", colour_id: "小豹纹", quantity: "2"}
"JW1501"
<tr data-id=​"1">​<td>​JW1501​</td>​<td class=​"code-quantity-total">​2​</td>​<td>​79.00​</td>​<td class=​"code-cost-total">​158.00​</td>​</tr>​
I have completely changed your printStock function to achieve your goal:
function printStock(model) {
$("#product_totals tr").each(function(){
var id = $("td:eq(0)", this).text().trim();
var price = parseFloat($("td:eq(2)", this).text());
var count = 0;
$.each(model, function(i, item){
if (item.product_id == id) count += (+item.quantity);
});
$("td:eq(1)", this).text(count);
$("td:eq(3)", this).text((count * price).toFixed(2));
});
var rows = $.map(model, function(item){
return [
"<td>" + item.product_id + "</td>",
"<td>" + item.size_id + "</td>",
"<td>" + item.colour_id + "</td>",
"<td>" + item.quantity + "</td>"
].join("");
});
var html = "<tr>" + rows.join("</tr><tr>") + "</tr>";
$('#stock_order tbody').html(html);
}
The main difference is that my code groups items in model by product_id for further counting.
Also refer my fiddle.

Select All checkbox only selects checkboxes that are currently in the page [not in other page indices]

I have a jquery dynatable. Here is the screenshot of my current table
My problem is that when I clicked the select all checkbox, the only checkboxes that are in the first page of the table are selected (in each row) but the others remain unselected. Here is my code so far:
// I have omitted the table head part for the sake of simplicity
/********************************
TABLE BODY
********************************/
var tableRows = "";
//iterate each result object
for (var row in result.results.bindings) {
tableRows += "<tr>";
//iterate each value
for (var key in result.results.bindings[row]) {
if (result.results.bindings[row].hasOwnProperty(key) && (resultSetVariables.length==0 || _.contains(resultSetVariables, "?" + key))) {
var value = "x";
if( result.results.bindings[row][key].value != undefined ) {
val = result.results.bindings[row][key].value;
if(val.match(regexURL)) {
value = '' + val.substr(val.lastIndexOf('/') + 1) + '';
}
else
value = val;
}
tableRows += "<td>" + value + "</td>";
}
}
tableRows+='<td><input type="checkbox" class="singleSelect"> </td>';
tableRows += "</tr>";
// console.log(tableRows);
};
$("#results_container").children().detach();
//create unique id
var id = Math.floor( Math.random()*99999 );
//append a new table to the DOM
$("#results_container").append('<table id="result_table' + id + '" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"><thead><tr></tr></thead><tbody></tbody></table>');
$("#results_container").append('<input type="button" class="btn" id="calculate_similarity" value="calculate_similarity" style="float:right;"/>');
$("#results_container").append("<label style='float:right;'><input class='mahoutSelection' id='selectAll' type='checkbox' value='selectAll' style='float:right;'>selectAll</label>");
//append head and body to tabley
$('#results_container table thead tr').append(tableHead);
$('#results_container table tbody').append(tableRows);
$('#results_container table tbody').append(tableRows);
//add the results table
this.resultTable = $('#results_container table').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>"
, "sPaginationType": "bootstrap"
, "oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
});
$('input[id="selectAll"]').on('click', function(){
if ( $(this).is(':checked') ) {
$("input[class=singleSelect]").each(function () {
$(this).prop("checked", true);
});
}
else {
$("input[class=singleSelect]").each(function () {
$(this).prop("checked", false);
});
}
});
So how could I fix it so that, when I click the select all, it checks all checkboxes ?

Categories

Resources