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
Related
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>
I am running a code that scrapes a form and then opens a new browser tab with the data using the format: fieldID, fieldLabel, filedValue
jQuery(document).ready(function(){jQuery('#helpdesk_ticket_submit').on('click', function(e){
submitText = "<table class='table'>"
submitText += ` <thead>
<tr>
<th scope="col">fieldID</th>
<th scope="col">fieldLabel</th>
<th scope="col">fieldValue</th>
</tr>
</thead>
<tbody>`
jQuery('#new_helpdesk_ticket input, #new_helpdesk_ticket select, #new_helpdesk_ticket textarea').each(
function(index){
var input = jQuery(this);
if (input.prev().is('textarea'))
if (input.attr('class').indexOf('hide') >= 0)
return;
let label = extractLabelText(input.attr('id')) //extrenal function to get the label of the field
submitText += "<tr><td>" + input.attr('id') + "</td><td>" + label + "</td><td> " + input.val() + "</td></tr>"
}
);
window.open().document.write(submitText);
there is nothing wrong with the code. My question is when I do window.open().document.write(submitText); how can I format the table with bootstrap?
I'm trying to output an array filled with Firestore objects onto a table, but just displays the last object above the table
<table class="darkTable">
<thead>
<tr>
<th>List of Available Shows</th>
</tr>
</thead>
<tbody>
<tr>
<div id="showList"></div>
</tr>
</tbody>
</table>
<script>
firebase.firestore().collection('TV Shows').get().then(snapshot => {
var i = 0;
var array = [];
snapshot.forEach(doc => {
array[i] = doc.data().show.name;
//console.log(doc.data().show.name);
//showList.innerHTML = array[i] + "<br />";
showList.innerHTML = '<td>' + array[i] + '</td>';
i++;
});
});
</script>
Is it the way I'm going about the td code lines?
assuming this markup:
<div id="showList"></div>
then it works about like this:
firebase.firestore().collection('TV Shows').get().then(snapshot => {
var showList = document.getElementById('showList');
var html = '<table class="darkTable"><thead><tr>';
html += '<th>List of Available Shows</th>';
/* add further columns into here, alike the one above. */
html += '</tr></thead><tbody>';
snapshot.forEach(doc => {
html += '<tr>';
html += '<td>' + doc.data().show.name + '</td>';
/* add further columns into here, alike the one above. */
html += '</tr>';
});
html += '</tbody></table>';
showList.append(html);
});
You're resetting the entire showList element with every iteration of the loop:
showList.innerHTML = '<td>' + array[i] + '</td>';
I suspect you mean to append to it each time instead or resetting it entirely each time. Maybe try building a string with each iteration, then set the whole thing after the loop is over.
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();
}
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.