Creating a simple table using JavaScript - javascript

I'm making a table using mostly Jquery and DataTables
I'm getting an error when calling $('#dataTable').dataTable(); but I don't see why this happens since I see my table correctly displayed but the DataTable script don't work so the table stays normal, instead having pagination,etc...
This is the error:
jquery.dataTables.js:1197 Uncaught TypeError: Cannot read property
'mData' of undefined
at HTMLTableCellElement. (jquery.dataTables.js:1197)
at Function.each (jquery-1.9.1.js:648)
at init.each (jquery-1.9.1.js:270)
at HTMLTableElement. (jquery.dataTables.js:1194)
at Function.each (jquery-1.9.1.js:648)
at init.each (jquery-1.9.1.js:270)
at init.DataTable [as dataTable] (jquery.dataTables.js:869)
at DisplayTable (accounts.js:19)
at TypesChanged (accounts.js:168)
at HTMLDocument. (accounts.js:171)
HTML:
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead class="dataTableHead">
<tr>
<%--JSON ARRAY CREATES THE TABLE--%>
</tr>
</thead>
<tfoot class="dataTableFooter">
<tr>
<%--JSON ARRAY CREATES THE TABLE--%>
</tr>
</tfoot>
<tbody class="dataTableBody">
<%--JSON ARRAY CREATES THE TABLE--%>
</tbody>
</table>
</div>
JavaScript
var types = [];
var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
function TypesChanged() {
selectedGroup = $('#group').val();
switch (selectedGroup) {
case "DDA":
types = ["400", "4044", "4045"];
break;
case "SAV":
types = ["300", "310"];
break;
case "MTG":
types = ["700", "710"];
break;
}
console.log("Selected group: " + selectedGroup + ", Types: " + types);
$('.dataTableHead').empty();
$('.dataTableFooter').empty();
$('.dataTableHead').append('<th class="text-center">Day</th>');
$('.dataTableFooter').append('<th class="text-center">Day</th>');
var columnNames = [];
$.each(types, function (index, value) {
columnNames += '<th class="text-center">Type ' + value + '</th>';
});
$('.dataTableHead').append(columnNames);
$('.dataTableFooter').append(columnNames);
DisplayTable();
}
TypesChanged();
function DisplayTable() {
var data;
//Table
$('.dataTableBody').empty();
for (var i = 1; i <= amountOfDayEnds; i++) {
data += '<tr align="center">';
data += '<td>' + i + '</td>';
$.each(types, function (index, value) {
data += '<td>' + '<input class="text-center amountOfAccounts" type="number" value="0" name="amountOfAccounts-' + value + '" data-error="Please, insert a value" required></td>'
});
data += '</tr>';
}
$('.dataTableBody').append(data);
$('#dataTable').dataTable();
}

Related

Highlight Searched Text in Table bug

So I'm working on a feature that require a user to type in a search item that will search a table for the term and highlight every occurrence. I found some code and got it to work, but I have a bug that I'm not sure how to resolve. In the search input if I hit back space to erase the search term, the unhighlight works until the last character letter. For example, I type in Demo and use back space to delete Demo, only the D is still highlighted.
Below are my code snippets.
NOTE: I have a search and render function that call the highlightActivity and renderReports functions
My CSS
.highlight {
background-color :gold
}
.highlight {
padding:1px 4px;
margin: 0 -4px;
}
My HTML
<input type="text" id="uniStringSearch" onkeyup="SearchAndRender()"></input>
<table id="currentReports" class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th><input name="select_all" id="selectedReports" value="1" type="checkbox" onclick="checkAll(this)" /> </th>
<th>DATE</th>
<th>SUMMARY TITLE</th>
<th>NAME</th>
<th>ACTIVITY TYPE</th>
<th>SUB ACTIVITY TYPE</th>
<th>ACTIVITY DETAILS</th>
</tr>
</thead>
<tbody id="reports"></tbody>
</table>
HighlightActivity Function
function highlightActivity() {
var searchTerm = $('#uniStringSearch').val();
var tableID = ''
switch (webPage) {
case 'reports':
tableID = '#currentReports';
break;
case 'analysis':
tableID = '#currentAnalysis';
break;
case 'statuses':
tableID = '#currentStatuses';
break;
default:
}
$(tableID).find('.highlight').removeClass('highlight');
$(tableID).find('tr td').each(function () {
if ((this).attr('data-search') !== 'false') {
var text = $(this).text();
var textLowerCase = text.toLowerCase();
var pos = textLowerCase.indexOf(searchTerm.toLowerCase());
var regex = new RegExp(searchTerm, 'ig');
text = text.replace(regex, (match, $1) => {
return '<span class="highlight">' + match + '</span>';
});
$(this).html(text);
if (pos !== -1) {
setTimeout(function () {
if ($(this).parent().find('.highlight').is(':empty')) {
$('.highlight').remove();
}
}.bind(this), 0);
}
else {
$(this).text(text);
}
}
if ($(this).parent().find('.highlight').length > 0) {
$(this).parent().show();
}
else {
$(this).parent().hide();
}
});
}
Render Reports Function
function renderReports(items) {
var html = '';
for (var i = 0; i < items.length; i++)
{
html = '<tr><td><input type="checkbox" id="selectedReports" onchange="chkInputChanged(event)"/></td>'
html += '<td>' + items[i].DateActivity + '</td>'
html += '<td>' + items[i].Name + '</td>'
html += '<td>' + items[i].ActivityType + '</td>'
html += '<td>' + items[i].SubActivityType + '</td>'
html += '<td id="searchActivityDetails">' + items[i].ActivityDetails + '</td></tr>'
}
$('#reports').empty();
$('#reports').append(html);
}
ALSO....one more thing, is there a way to have my highlight function to target a specific column? For example Summary Title and Activity Details

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>

jQuery sum the values of table rows

hello i have this table
i want to get the total of each row in the total column
jQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#full_year_cost');
var budget_total_month = $('#share_cost');
var budget_per_lead = $('#cost_per_lead');
leads.append('<th>' + value.olxTotal + '</th>');
budget_total_year.append('<th>' + value.budget_total_year + '</th>');
budget_total_month.append('<th>' + value.budget_total_month + '</th>');
budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
})
})
HTML
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="full_year_cost">
<th>Full Year Cost</th>
</tr>
<tr id="share_cost">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cost_per_lead">
<th>Cost per Lead</th>
</tr>
</tbody>
i was going to calculate the total through php but i though it can be easier
using jQuery just putting the sum of each row at the end
Thank you very much
Create variables before the loop. add to the variables in the loop and then assign the sum at the end.
$.get('/dashboard/costs', function(data){
var sumLeads = 0;
var sumFullYearCost = 0;
var sumShareCost = 0;
var sumCostPerLead = 0;
var tr_leads = $('#leads');
var tr_budget_total_year = $('#full_year_cost');
var tr_budget_total_month = $('#share_cost');
var tr_budget_per_lead = $('#cost_per_lead');
$.each(data,function(i,value){
tr_leads.append('<th>' + value.olxTotal + '</th>');
tr_budget_total_year.append('<th>' + value.budget_total_year + '</th>');
tr_budget_total_month.append('<th>' + value.budget_total_month + '</th>');
tr_budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
sumLeads += value.olxTotal;
sumFullYearCost += value.budget_total_year;
sumShareCost += value.budget_total_month;
sumCostPerLead += value.budget_per_lead;
});
tr_leads.append('<th>' + sumLeads + '</th>');
tr_budget_total_year.append('<th>' + sumFullYearCost + '</th>');
tr_budget_total_month.append('<th>' + sumShareCost + '</th>');
tr_budget_per_lead.append('<th>' + sumCostPerLead + '</th>');
});
Example for leads row using Array.map and Array.reduce. Use jQuery to get the td elements.
var leads = $('#leads');
const total = leads.children('td').toArray().map(x=>Number(x.innerHTML)).reduce((sum, x) => sum + x)
leads.append(`<th>${total}</th>`);
Try something like this.
$('#tableData-marketMonth tr').each(function () {
var row = $(this);
var rowTotal = 0;
$(this).find('th').each(function () {
var th = $(this);
if ($.isNumeric(th.text())) {
rowTotal += parseFloat(th.text());
}
});
row.find('th:last').text(rowTotal);
});
NOTE: change 'th' to 'td' if you have td's. Looking at your jquery, it looks like you are appending th's.
You can use my written code to vote if you like it...
HTML
<table>
<thead>
<tr>
<th>MAX ATK</th>
<th>MAX DEF</th>
<th>MAX HP</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat">8170</td>
<td class="combat">6504</td>
<td class="combat">6050</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">8500</td>
<td class="combat">10200</td>
<td class="combat">7650</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">9185</td>
<td class="combat">7515</td>
<td class="combat">9185</td>
<td class="total-combat"></td>
</tr>
</tbody>
</table>
jquery
$(document).ready(function () {
//iterate through each row in the table
$('tr').each(function () {
//the value of sum needs to be reset for each row, so it has to be set inside the row loop
var sum = 0
//find the combat elements in the current row and sum it
$(this).find('.combat').each(function () {
var combat = $(this).text();
if (!isNaN(combat) && combat.length !== 0) {
sum += parseFloat(combat);
}
});
//set the value of currents rows sum to the total-combat element in the current row
$('.total-combat', this).html(sum);
});
});

How to Add data in tbody using Javascript only

This is my Javascript function:
function SaveCustomdata() {
var customName = document.getElementById("lblNAME").value;
var customEmail = document.getElementById("lblEmail").value;
var customContectNo = document.getElementById("lblContectNO").value;
var row = "";
row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>';
document.getElementById("Customdata").appendChild(row);
}
HTML code where I want to append the data:
<table>
<thead>
<tr>
<th style=" color:#01A0DF; padding-right:60px;">Name</th>
<th style=" color:#01A0DF; padding-right:70px;">Email</th>
<th style=" color:#01A0DF; padding-right:90px;">Contect/Mobile No</th>
<td>
<input type="button" id="btnclick" value="Add" onclick="AddRecord()" />
</td>
</tr>
</thead>
<tbody id="Customdata"></tbody>
</table>
Getting an error:
0x800a139e - JavaScript run time error: Hierarchy Request Error
With the use of innerHTML:
function SaveCustomdata() {
var customName = document.getElementById("lblNAME").value;
var customEmail = document.getElementById("lblEmail").value;
var customContectNo = document.getElementById("lblContectNO").value;
var row = "";
row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>';
// get the current table body html as a string, and append the new row
var html = document.getElementById("Customdata").innerHTML + row;
// set the table body to the new html code
document.getElementById("Customdata").innerHTML = html;
}
Here you have a fiddle. Let us know if it helped you a bit.Basically you could use .innerHTML for appending strings as elements, because this gets "evaluated by browser".Otherwise you would have to do it programmatically as mentioned in the comments

How to remove the duplicates for append in my html?

I have create javascript to calulate the total of ext. form json but I have problem is it append twice to #total div I don't know what cause maybe because of renderTable function.can someone help me ??
HTML
<div data-role="collapsible" data-collapsed="true" id="poInfos">
<h3 id="poInfo"></h3>
<table data-role="table" id="productOrders" data-mode="reflow">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Qty.</th>
<th>Ext.</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<div id="total">
</div>
</div>
</div>
</div>
javascript
//render table view all PO for vendor
function renderTable(data){
var $table = $('#productOrders tbody');
var plist = data[0].pslList;
for(var i in plist) {
var row = $('<tr><td>' + plist[i].prodcd + '</td><td>' + plist[i].prodname + '</td><td class="dollars">' + numberToCurrency(plist[i].price) + '</td><td>' + plist[i].qty + '</td><td>' + numberToCurrency(plist[i].ext) + '</td></tr>');
$table.append(row);
calculateTotal(data);
}
}
//calculateTotal
function calculateTotal(data)
{
var $totalDiv = $('#total');
var tax = 0.00;
var sub = 0.00;
var totalsub_tax = 0.00;
var plist = data[0].pslList;
for(var i in plist) {
sub += plist[i].ext;
totalsub_tax = sub +tax;
}
$totalDiv.append("<strong>Sub:</strong>"+numberToCurrency(sub)+"<br/><strong>Total:</strong>"+numberToCurrency(totalsub_tax) +"<br/>");
}
//convert numberToCurrency
function numberToCurrency(amount) {
var thousandsSeparator = ","
var currencyNum = "";
var amountString = amount.toString();
var digits = amountString.split("");
var countDigits = digits.length;
var revDigits = digits.reverse();
for(var i=0; i<countDigits; i++) {
if ((i%3 == 0) && (i !=0)) {
currencyNum += thousandsSeparator+revDigits[i];
} else {
currencyNum += digits[i];
}
};
var revCurrency = currencyNum.split("").reverse().join("");
var finalCurrency = "$"+revCurrency;
return finalCurrency;
}
});
You're running the function calculateTotal() for EACH item instead of after the items have been dealt with.
for(var i in plist) {
var row = $('<tr><td>' + plist[i].prodcd + '</td><td>' + plist[i].prodname + '</td><td class="dollars">' + numberToCurrency(plist[i].price) + '</td><td>' + plist[i].qty + '</td><td>' + numberToCurrency(plist[i].ext) + '</td></tr>');
$table.append(row);
// not here calculateTotal(data);
}
calculateTotal(data); // here
Your call to calculateTotal(data) is within the loop over plist. You should move it outside.

Categories

Resources