Populate view with different values in js - javascript

I am writing a website and need to work with a big data mass. I sort this with special algorithmics and now I want to populate one whole table, but put in different values.
I already have this HTML piece:
<div class='main_has_permission' id="main_has_permission">
<div class='main_padding' id="main_padding">
<div class="noten_tabelle_permission" id="noten_tabelle_permission">
<h1 id="member_name"></h1>
<table id="grades_table" style="width:100%">
<tr>
<th>Fach</th>
<th>mündlich</th>
<th>Klausur</th>
</tr>
</table>
</div>
</div>
</div>
The main_padding div is the div in which the whole table should be populated.
With the following code, I get the data and call a function to add the values to the table:
db.collection("users")
.doc(el)
.collection("grades")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
const data = doc.data();
addToTable("grade_table" + table_number, doc.id, data.mdl, data.klu);
});
});
Finally here is the function who adds the values to the table:
function addToTable(table_name, subject, mdl, klu) {
var subject_name = getSubjectByNumber(subject);
var short_subject = getSubjectShortByNumber(subject);
//Zeile erstellen
var y = document.createElement([short_subject]);
y.setAttribute("id", [short_subject]);
document.getElementById([table_name]).appendChild(y);
//Spalten in einer Zeile
var y = document.createElement("TR");
y.setAttribute("id", [short_subject]);
//Spalten in einer Zeile
var cE = document.createElement("TD");
var tE = document.createTextNode([subject_name]);
cE.appendChild(tE);
y.appendChild(cE);
var a = document.createElement("TD");
var b = document.createTextNode([mdl]);
a.appendChild(b);
y.appendChild(a);
var c = document.createElement("TD");
var d = document.createTextNode([klu]);
c.appendChild(d);
y.appendChild(c);
document.getElementById("grades_table").appendChild(y);
}
Now...How to populate the table by putting in different values?
Thanks in advance.

Related

How to present data by DOM not by table

I have a doubt in the application I'm creating, I'm working with an Oracle database, and I'm bringing the information from the database and presenting it on the screen through a table, but I wanted to try to work separately with this data, for example creating a paragraph and display a value.
I was only able to present the data through a table, is there another way? Thanks a lot if anyone can help me with this.
I accept all tips to improve the code.
My Index.html page
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apontamentos da Produção</title>
<link rel="stylesheet" type="text/css" href="styles.css" media="screen" />
</head>
<body>
<meta http-equiv="refresh" content="5">
<div id="data"></div>
<div class="grid-container">
<div class="container">
<div class="texto"> PAINEL-1 | APONTAMENTOS DA PRODUÇÃO</div>
<div class="clock"></div>
</div>
</div>
<div class="progress">
<div class="progress-bar"></div>
</div>
<br>
<!-- Tabela principal, apresentando os apontamentos -->
<table id="table" class="tablePrincipal">
<tr class="trPrincipal">
<th class="th2" style="width: 11%;">Data</th>
<th class="th2" style="width: 8%; ">Hora</th>
<th class="th2" style="width: 5%;">Orig.</th>
<th class="th2" style="width: 8%;">O.P.</th>
<th class="th2" style="width: 10%;">Produto</th>
<th class="th2" style="width: 8%;">Deriv.</th>
<th class="th2" style="width: 9%;">Peso (TN)</th>
<th class="th2" style="width: 7%;">Refugo (TN)</th>
<th class="th2" style="width: 13%;">Lote</th>
<th class="th2" style="width: 60%;;">Operador</th>
</tr>
</table>
<br>
</body>
<script>
// Tabela de apontamentos. Listagem.
// Aqui é onde é feito o push de informações, chamando pelo caminho e colocando o ID da tabela que ele vai levar as informações
window.onload = function () {
fetch('http://localhost:3000/teste')
.then(response => response.json())
.then(data => {
console.log(data);
var table = document.getElementById('table');
// Primeiro define a variavel, e coloca o comando para inserir uma linha, é tudo organizado por rows
for (var i = 0; i < 7; i++) {
var row = table.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
var cell8 = row.insertCell(7);
var cell9 = row.insertCell(8);
var cell10 = row.insertCell(9);
// Queria trabalhar com os dados separadamente, tentar criar um <p> e colocar um dado para apresentar.
// Queria tentar fazer um calculo com essa variável, mas não funciona assim
var cell11 = cell7 * 2;
// Aqui chama a variavel e coloca a linha na tabela
cell1.innerHTML = data[i][0];
cell2.innerHTML = data[i][1];
cell3.innerHTML = data[i][2];
cell4.innerHTML = data[i][3];
cell5.innerHTML = data[i][4];
cell6.innerHTML = data[i][5];
cell7.innerHTML = data[i][6];
cell8.innerHTML = data[i][7];
cell9.innerHTML = data[i][8];
cell10.innerHTML = data[i][9];
}}
)}
</script>
</html>
This is my Index.js, in it I'm doing the select and sending the data
const express = require('express');
const oracledb = require('oracledb');
const app = express();
var cors = require('cors')
app.use(cors())
const http = require('http');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// Connection details for the Oracle database
const connectionString = '';
const user = '';
const password = '';
// Connect to the database
app.get('/teste', (req, res) => {
// within the endpoint, query the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function teste(err, connection) {
if (err) {
console.error(err.message);
return;
}
console.log('Conexão deu certo!');
const query = 'SELECT DATREA,HORREA,CODORI,NUMORP,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OPERADOR from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
return;
}
console.log('Banco de Dados Atualizado');
console.log();
// return the results to the user
res.json(result.rows);
});
});
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Assumptions:
Since the scenario cannot be exactly reproduced I will focus on the client side only taking for granted that your backend endpoint will correctly return an array like: data[iRow][iColumn]
Such assumption came from lines like this cell1.innerHTML = data[i][0];
data example statically defined:
I'm not perfectly sure if data is just an array of array or there's some way to address the columns value by column name somehow. Anyway here we'll stick with the plain array paradigm since it seemed to work by your own words.
Here we define a data array with 2 rows having 10 columns each:
//the array you are supposed to receive from your ajax call
const data = [
//first row of cells
[
'rowX_cell(01)',
'rowX_cell(02)',
'rowX_cell(03)',
'rowX_cell(04)',
'rowX_cell(05)',
'rowX_cell(06)',
'rowX_cell(07)',
'rowX_cell(08)',
'rowX_cell(09)',
'rowX_cell(10)',
],
//second row of cells
[
'rowY_cell(01)',
'rowY_cell(02)',
'rowY_cell(03)',
'rowY_cell(04)',
'rowY_cell(05)',
'rowY_cell(06)',
'rowY_cell(07)',
'rowY_cell(08)',
'rowY_cell(09)',
'rowY_cell(10)',
],
]
Defining columns name and order:
I can also say the order of columns fetched from DB since the SQL query was shown and that's the ordered list:
DATREA,HORREA,CODORI,NUMORP,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OPERADOR
That we are defining in js as an array of strings like this:
//ordered list of columns in the same order as the cols in data are supposed to be
const columnNames = ['DATREA','HORREA','CODORI','NUMORP','CODPRO','CODDER','QTDRE1','QTDRFG','CODLOT','OPERADOR'];
Transform row array to object:
Transforming rows data to an array of objects having as properties the row columns named as the list of columns shown before:
function getRowObject(row){
const rowObject = {};
//for each col in columnNames
columnNames.forEach((col, i)=>{
//set the prop of rowObject named as col = the value at the i position in row
rowObject[col] = row[i];
});
return rowObject;
}
that for the first row of data (data[0]) would return an object like this:
{
"DATREA": "rowX_cell(01)",
"HORREA": "rowX_cell(02)",
"CODORI": "rowX_cell(03)",
"NUMORP": "rowX_cell(04)",
"CODPRO": "rowX_cell(05)",
"CODDER": "rowX_cell(06)",
"QTDRE1": "rowX_cell(07)",
"QTDRFG": "rowX_cell(08)",
"CODLOT": "rowX_cell(09)",
"OPERADOR": "rowX_cell(10)"
}
How to show that data in the document?
You have infinite ways depending on what's exactly the goal. Actually you didn't need to transform the array to object to begin with, but it made it easier to access its columns by name instead of using a index number.
Anyway if for example you needed to show each row as the content of an individual paragraph having as content the concatenation of all its columns data:
function appendRowsAsParagraphsInTarget(target, rowObjects){
//you can loop through all the rows and print them on screen
rowObjects.forEach( row => {
//here we are converting the row object back to a list of values
values = columnNames.map( columnName => row[columnName] );
//here to a single string where values are separated by ', ' and wrapped in []
values = values.map( value => `[${value}]`);
values = values.join(', ');
//append the newly created p in target
const p = document.createElement('p');
p.textContent = values;
target.append(p);
});
}
Demo:
Here's a live demo of what said so far:
//the array you are supposed to receive from your ajax call
const data = [
//first row of cells
[
'rowX_cell(01)',
'rowX_cell(02)',
'rowX_cell(03)',
'rowX_cell(04)',
'rowX_cell(05)',
'rowX_cell(06)',
'rowX_cell(07)',
'rowX_cell(08)',
'rowX_cell(09)',
'rowX_cell(10)',
],
//second row of cells
[
'rowY_cell(01)',
'rowY_cell(02)',
'rowY_cell(03)',
'rowY_cell(04)',
'rowY_cell(05)',
'rowY_cell(06)',
'rowY_cell(07)',
'rowY_cell(08)',
'rowY_cell(09)',
'rowY_cell(10)',
],
]
//ordered list of columns in the same order as the cols in data are supposed to be
const columnNames = ['DATREA','HORREA','CODORI','NUMORP','CODPRO','CODDER','QTDRE1','QTDRFG','CODLOT','OPERADOR'];
//transforming the original array of rows as array of objects where each one as col data as properties
const rowObjects = data.map( row => getRowObject(row) );
console.log(rowObjects);
//appending the rowObjects as p paragraph to #output_rows
const target = document.getElementById('output_rows');
appendRowsAsParagraphsInTarget(target, rowObjects);
function appendRowsAsParagraphsInTarget(target, rowObjects){
//you can loop through all the rows and print them on screen
rowObjects.forEach( row => {
//here we are converting the row object back to a list of values
values = columnNames.map( columnName => row[columnName] );
//here to a single string where values are separated by ', ' and wrapped in []
values = values.map( value => `[${value}]`);
values = values.join(', ');
//append the newly created p in target
const p = document.createElement('p');
p.textContent = values;
target.append(p);
});
}
function getRowObject(row){
const rowObject = {};
//for each col in columnNames
columnNames.forEach((col, i)=>{
//set the prop of rowObject named as col = the value at the i position in row
rowObject[col] = row[i];
});
return rowObject;
}
.label{
font-weight: bold;
}
#output_rows{
}
#output_rows > p{
border: solid 1px lightgray;
margin-bottom: 1em;
}
<p class="label">Showing all the table rows as p elements</p>
<div id="output_rows"></div>

How to display objects from array into HTML table

enter image description hereI am working on a Shopping Cart problem and I have a table in HTML to input various objects in an Array. I want to create a "edit" button to display the specific array info back on the table.
I am working on just Visual Studio Code and Javascript. No other tools used as this is the fundamentals for my course.
So what should I code in editAdminFunc to display the objects in HTML?
Please see my code for info.
// create a flower array
var flowerArray=[];
// declare a member object
function flower(id, name, desc, price, stock, image){
this.id = id; //id
this.name = name; //name
this.desc= desc; //description
this.price = price; //price
this.stock = stock; //quantity
this.image = image; //image
}
function addFlower(){
alert("addFlower function is being triggered!");
var newFlower = new flower(
document.getElementById("memId").value,
document.getElementById("memName").value,
document.getElementById("memDesc").value,
document.getElementById("memPrice").value,
document.getElementById("memStock").value,
document.getElementById("memImage").src,
);
flowerArray.push(newFlower);
console.log(flowerArray);
}
//this function is to show the flowers in list format (for admin view)
function listFlowerFunc(){
alert("listFlowerFunc is being triggered!");
var displayText = "<table border=1, align = center>";
displayText += "<tr><th>Product ID</th><th>Name</th><th>Description</th><th>Unit Price</th><th>Stock</th><th>Image</th><th>Actions</th></tr>";
for (var i=0; i<flowerArray.length; i++){
displayText = displayText + "<tr><td>"+flowerArray[i].id+"</td><td>"+flowerArray[i].name+"</td><td>"+flowerArray[i].desc+"</td><td>"+flowerArray[i].price+"</td><td>"+flowerArray[i].stock+"</td><td>"+flowerArray[i].src+"</td><td><button onclick =editAdminFunc()>edit</button><button onclick =deleteAdminFunc()>delete</button></td></tr>"
}
displayText = displayText+"</table>";
document.getElementById("productlist").innerHTML = displayText;
}
//editAdminFunc
function editAdminFunc(i){
alert("editAdminFunc() has been triggered!")
document.getElementById("memId").value = ""; //to display array objects in the form
document.getElementById("memName").value = "";
document.getElementById("memDesc").value= "";
document.getElementById("memPrice").value= "";
document.getElementById("memStock").value= "";
document.getElementById("memImage").src= "";
}
<div id="admin" align="center">
<p>
<button onclick='showProductForm()'>Add Products</button> | <button id ="flowerListId" onclick="listFlowerFunc()">List Products</button>
</p>
<div id="productlist">
</div>
<br>
<div id="productForm" align="center">
<table id = "prodTable" border ="1">
<tr><td align="right">Product ID:</td><td><input type="text" id="memId" size="35"/></td></tr>
<tr><td align="right">Name:</td><td><input type="text" id="memName" size="35"/></td></tr>
<tr><td align="right">Description:</td><td><input type="text" id="memDesc" size="35"/></td></tr>
<tr><td align="right">Unit Price($):</td><td><input type="text" id="memPrice" size="35"/></td></tr>
<tr><td align="right">Stock:</td><td><input type="text" id="memStock" size="35"/></td></tr>
<tr><td align="right">Image:</td><td><input type="file" id="memImage"/></td></tr>
<tr><td>&nbsp</td>
<td><button id="clearFormBtn" onclick="clearFormFunc()">Clear</button>
<button id="addProdBtn" onclick="addFlower()">Add</button>
<button id="updateProdBtn" onclick="editHtmlTableSelected()">Update</button>
</td></tr>
</table>
</div>
</div>
the right way to create an element in javascript, would be something like that
<div class="some"></div>
function addElement () {
// create new "p" element
var newP = document.createElement("p");
// add content -- the data you want display
var newContent = document.createTextNode("hello, how are you?");
newP.appendChild(newContent); //add content inside the element.
// add the element and content to DOM
var currentDiv = document.getElementById("some");
document.body.insertBefore(newP, currentDiv);
}
addElement();
https://developer.mozilla.org/es/docs/Web/API/Document/createElement
Now, if we adapt that information to the context of the tables, we can do it on this way to generate the data dynamically
arr = [
'item 1',
'item 2',
'item 3',
'item 4',
'item 5'
];
function addElement () {
arr.forEach(function(el,index,array){
let tableRef = document.getElementById('some');
// Insert a row at the end of the table
let newRow = tableRef.insertRow(-1);
// Insert a cell in the row at index 0
let newCell = newRow.insertCell(0);
// Append a text node to the cell
let newText = document.createTextNode(el);
newCell.appendChild(newText);
});
}
addElement();
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell
link to demo: Fiddle

Handling the table from a html form with javascript

<table id="production">
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
</table>
Product Name:
Product Quanitity:
Add
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table = document.getElementById("production");
var rows = table.rows;
var cell1 = rows[0].insertCell(-1);
var cell2 = rows[1].insertCell(-1);
cell1.innerHTML = prdn;
cell2.innerHTML = prdq;
}
I need someone help me understand how I can insert data in separate column in database; suppose I have a table of three rows and three columns, columns are created by using td tags, now in the first and last columns elements are predefined and so any data should insert in the second column of the table after clicking the button. because the code above is inserting the data in raw cells by default.
i am adding the fiddle here
http://jsfiddle.net/3e7rh/2/
As you can see here, you need to add in the last - 1 column.
http://jsfiddle.net/3e7rh/8/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].insertCell(rows[0].cells.length - 1);
var cell2=rows[1].insertCell(rows[1].cells.length - 1);
cell1.innerHTML=prdn;
cell2.innerHTML=prdq;
}
Update:
http://jsfiddle.net/3e7rh/10/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].cells[1].textContent=prdn;
var cell2=rows[1].cells[1].textContent=prdq;
}
Get the table. Iterate over all rows and fill in the first td (Because you are using th as the first one)
var table = document.getElementById("production")
rows = table.getElementsByTagName("tr");
for(var i=0;i<rows.length;i++)
{
columns = rows[i].getElementsByTagName("td");
columns[0].textContent="text"; //First Td second column in your case
}
Jsfiddle:http://jsfiddle.net/7xs6v/1/
I am assuming you want to fill the same text in every first td(second column). If you want individual then you can use the index specificallyinstead of iterating over for loop

Populate 2 tables with 2 sets of data when 1 field matches in both sets

I'm using Josh Fraser's Backwards compatible window.postMessage() (http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage) and I'm having trouble.
I have 2 iframes on a page and both iframes send different data to the same parent page. In other words, there are 2 XD.receivemessage functions getting 2 different messages from 2 different iframes. Here's a shortened version of my code:
<iframe id="IFRAME1" src="https://www.DOMAIN.com/PAGENAMEFIRST.php"></iframe>
<iframe id="IFRAME2" src="https://www.DOMAIN.com/PAGENAMESECOND.php"></iframe>
<div id="firstTable">
<table>
<tr>
<th>Name</th>
<th>Address</th>
<th>ID</th>
</tr>
<tr>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
</tr>
</table>
</div>
<div id="secondTable">
<table>
<tr>
<th>Email</th>
<th>Twitter Handle</th>
<th>ID</th>
</tr>
<tr>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
//FIRST DATA PULL
var encodeUriFirst = encodeURIComponent(document.location.href);
var getMessageFirst = 'https://www.DOMAIN.com/PAGENAMEFIRST.php#' + encodeUriFirst;
$("#IFRAME1").attr('src',getMessageFirst);
XD.receiveMessage(function(getMessageFirst){
var getDataFirst = getMessageFirst.data;
var getDataFirstEach = new Array();
for(var a=0; a<getDataFirst.length; a++){
getDataFirstEach = getDataFirst.split("~,~");
$('div#firstTable table td:nth-child(0)').text(getDataFirstEach[0].replace(/[~]/g,""));
}
}, 'https://www.DOMAIN.com');
//SECOND DATA PULL
var encodeUriSecond = encodeURIComponent(document.location.href);
var getMessageSecond = '//www.DOMAIN.com/PAGENAMESECOND.php#' + encodeUriSecond;
$("#IFRAME2").attr('src',getMessageSecond);
XD.receiveMessage(function(getMessageSecond){
var getDataSecond = getMessageSecond.data;
var getDataSecondEach = new Array();
for(var a=0; a<getDataFirst.length; a++){
getDataSecondEach = getDataSecond.split("~,~");
$('div#secondTable table td:nth-child(0)').text(getDataSecondEach[0].replace(/[~]/g,""));
}
}, 'https://www.DOMAIN.com');
});
</script>
Please keep in mind that I've scaled back the code significantly. Each getDataFirst or getDataSecond
It actually works as far as getting the data from both iframes (send/receive both work). My data comes through in the format ~name~,~address~,~ID~ for the first set of data and ~email~,~twitter~,~ID~ for the second set.
I'm trying to get the data to populate the 2 tables. The For loops look for the ID in the table and if the ID matches, it fills in the other fields associated with that ID. In some cases, the ID from the first data set will be the same as the ID from the second data set. When that happens, the for loops place the data in both tables instead of the appropriate one. I'm wondering why this would happen since I'm specifically targeting the table inside either $('div#firstTable') or $('div#secondTable') for the output. For example:
$('div#firstTable table td:nth-child(0)').text(getDataFirstEach[0]);
inside the For loop is placing getDataFirstEach[0] into both the firstTable and secondTable tables?
Can anyone tell me why?
AS REQUESTED, HERE IS THE FULL JS:
var encodeUriGifts = encodeURIComponent(document.location.href);
var giftsMessage = '//www.DOMAIN.org/firstpage.php#' + encodeUriGifts;
$("#IFRAME1").attr('src',giftsMessage);
XD.receiveMessage(function(giftsMessage){
var getDataGifts = giftsMessage.data;
var currentRecordGifts = new Array();
var getGiftsLines = getDataGifts.split("|"); //LINES OF DATA ARE PIPE SEPARATED
for(var bCnt=0;bCnt < getGiftsLines.length;bCnt++){
var getGiftsEach = getGiftsLines[bCnt].split("`,`"); //EACH ITEM IS SEPARATED BY `,`
for(var cCnt=0;cCnt < getGiftsEach.length;cCnt++){
if (getGiftsEach[cCnt]!=="" && getGiftsEach[cCnt]!=="undefined"){
currentRecordGifts[bCnt] = " <td class='giftamount'>"+getGiftsEach[1]+"</td><td class='giftdate'>"+getGiftsEach[2].replace(/[`]/g,"")+"</td>";
}
if (cCnt==2) {
var thisGiftsID = getGiftsEach[0].replace(/[`]/g,"");
$('#firstTable table td:contains("'+thisGiftsID+'")').closest('tr').find('td:nth-child(3)').after(currentRecordGifts[bCnt]);
}
}
if (bCnt==0){
$('#firstTable table th:nth-child(3)').after('<th class="BBListingHeading DirectoryListingHeading" scope="col" style="white-space: nowrap;">Last Gift Amount</th><th class="BBListingHeading DirectoryListingHeading" scope="col" style="white-space: nowrap;">Last Gift Date</th>');
}
}
}, 'https://www.DOMAIN.org');
var encodeUriChanges = encodeURIComponent(document.location.href);
var changesMessage = '//www.DOMAIN.org/secondpage.php#' + encodeUriChanges;
$("#IFRAME2").attr('src',changesMessage);
XD.receiveMessage(function(changesMessage){
var getDataChanges = changesMessage.data;
var currentRecordChanges = new Array();
var getChangesLines = getDataChanges.split("|");
$('#secondTable table tr td:nth-child(3)').each( function() {
$('#secondTable table tr td:nth-child(3)').after('<td class="BBListingItem DirectoryListingItem" style="white-space: nowrap;"><ul class="changes"></ul></td>');
});
for(var dCnt=0;dCnt < getChangesLines.length;dCnt++){
var getChangesEach = getChangesLines[dCnt].split("`,`");
for(var eCnt=0;eCnt < getChangesEach.length;eCnt++){
if (getChangesEach[eCnt]!=="" && getChangesEach[eCnt]!=="undefined"){
currentRecordChanges[dCnt] = "<li class='change'>"+getChangesEach[2]+" ("+getChangesEach[1].replace(/[`]/g,"")+")</li>";
}
if (eCnt==2) {
var thisChangesID = getChangesEach[0].replace(/[`]/g,"");
$('#secondTable table td:contains("'+thisChangesID+'")').closest('tr').find('td ul.changes').append(currentRecordChanges[dCnt]);
}
if (dCnt==0){
$('#changesdiv .DirectoryListingTable th:nth-child(3)').after('<th class="BBListingHeading DirectoryListingHeading" scope="col" style="white-space: nowrap;">Change Details</th>');
}
}
}
}, 'https://www.DOMAIN.org');

Creating a Shopping Cart using only HTML/JavaScript

I'm not sure what to do in order to complete this project. I need to create a shopping cart that uses only one HTML page. I have the table set up showing what is being sold but where I am lost is the JavaScript.
I don't know how to link the "Add to Cart" button with all the necessary data( The name, description, and price) to be able to add it to the cart. I don't need to be able to remove it from the cart, but it does need to show the total. After searching online for a few answers, I've tried some things but just cannot figure it out.
Any help is definitely appreciated because I am completely lost at this point and am new to JavaScript in general.
This is the jsFiddle but that was a little confusing to me, because it's working differently on there than if I just went to Run in Notepad++
jsFiddle: http://jsfiddle.net/renavi/ATjvt/5/
function AddtoCart() {
console.log('hi');
var x = document.getElementById('Items');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild(new_row);
}
The direct file is here
Pastebin: http://pastebin.com/sutGWjSY
You simply need to use simpleCart
It is a free and open-source javascript shopping cart that easily integrates with your current website.
You will get the full source code at github
For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.
Example of your code then becomes;
function AddtoCart() {
var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;
$row = $("#Items td:first").clone(true);
$cells = $row.find("td");
$cells.get(0).html( len );
$inp1 = $cells.get(1).find("input:first");
$inp1.attr("id", $inp1.attr("id") + len).val("");
$inp2 = $cells.get(2).find("input:first");
$inp2.attr("id", $inp2.attr("id") + len).val("");
$("#Items").append($row);
}
I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.
I would use the libraries already created specifically for js shopping carts if I were you though.
To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?
I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)
I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.
You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm
You can try following approach:
//create array that will hold all ordered products
var shoppingCart = [];
//this function manipulates DOM and displays content of our shopping cart
function displayShoppingCart(){
var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
//ensure we delete all previously added rows from ordered products table
while(orderedProductsTblBody.rows.length>0) {
orderedProductsTblBody.deleteRow(0);
}
//variable to hold total price of shopping cart
var cart_total_price=0;
//iterate over array of objects
for(var product in shoppingCart){
//add new row
var row=orderedProductsTblBody.insertRow();
//create three cells for product properties
var cellName = row.insertCell(0);
var cellDescription = row.insertCell(1);
var cellPrice = row.insertCell(2);
cellPrice.align="right";
//fill cells with values from current product object of our array
cellName.innerHTML = shoppingCart[product].Name;
cellDescription.innerHTML = shoppingCart[product].Description;
cellPrice.innerHTML = shoppingCart[product].Price;
cart_total_price+=shoppingCart[product].Price;
}
//fill total cost of our shopping cart
document.getElementById("cart_total").innerHTML=cart_total_price;
}
function AddtoCart(name,description,price){
//Below we create JavaScript Object that will hold three properties you have mentioned: Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name=name;
singleProduct.Description=description;
singleProduct.Price=price;
//Add newly created product to our shopping cart
shoppingCart.push(singleProduct);
//call display function to show on screen
displayShoppingCart();
}
//Add some products to our shopping cart via code or you can create a button with onclick event
//AddtoCart("Table","Big red table",50);
//AddtoCart("Door","Big yellow door",150);
//AddtoCart("Car","Ferrari S23",150000);
<table cellpadding="4" cellspacing="4" border="1">
<tr>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="0">
<thead>
<tr>
<td colspan="2">
Products for sale
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
Table
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
</td>
</tr>
<tr>
<td>
Door
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
</td>
</tr>
<tr>
<td>
Car
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
</td>
</tr>
</tbody>
</table>
</td>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
<thead>
<tr>
<td>
Name
</td>
<td>
Description
</td>
<td>
Price
</td>
</tr>
</thead>
<tbody id="orderedProductsTblBody">
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right" id="cart_total">
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</table>
Please have a look at following free client-side shopping cart:
SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.
Documentation
http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html
Hope you will find it useful.
Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox
cart.js
var cart = {
// (A) PROPERTIES
hPdt : null, // HTML products list
hItems : null, // HTML current cart
items : {}, // Current items in cart
// (B) LOCALSTORAGE CART
// (B1) SAVE CURRENT CART INTO LOCALSTORAGE
save : function () {
localStorage.setItem("cart", JSON.stringify(cart.items));
},
// (B2) LOAD CART FROM LOCALSTORAGE
load : function () {
cart.items = localStorage.getItem("cart");
if (cart.items == null) { cart.items = {}; }
else { cart.items = JSON.parse(cart.items); }
},
// (B3) EMPTY ENTIRE CART
nuke : function () {
if (confirm("Empty cart?")) {
cart.items = {};
localStorage.removeItem("cart");
cart.list();
}
},
// (C) INITIALIZE
init : function () {
// (C1) GET HTML ELEMENTS
cart.hPdt = document.getElementById("cart-products");
cart.hItems = document.getElementById("cart-items");
// (C2) DRAW PRODUCTS LIST
cart.hPdt.innerHTML = "";
let p, item, part;
for (let id in products) {
// WRAPPER
p = products[id];
item = document.createElement("div");
item.className = "p-item";
cart.hPdt.appendChild(item);
// PRODUCT IMAGE
part = document.createElement("img");
part.src = "images/" +p.img;
part.className = "p-img";
item.appendChild(part);
// PRODUCT NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "p-name";
item.appendChild(part);
// PRODUCT DESCRIPTION
part = document.createElement("div");
part.innerHTML = p.desc;
part.className = "p-desc";
item.appendChild(part);
// PRODUCT PRICE
part = document.createElement("div");
part.innerHTML = "$" + p.price;
part.className = "p-price";
item.appendChild(part);
// ADD TO CART
part = document.createElement("input");
part.type = "button";
part.value = "Add to Cart";
part.className = "cart p-add";
part.onclick = cart.add;
part.dataset.id = id;
item.appendChild(part);
}
// (C3) LOAD CART FROM PREVIOUS SESSION
cart.load();
// (C4) LIST CURRENT CART ITEMS
cart.list();
},
// (D) LIST CURRENT CART ITEMS (IN HTML)
list : function () {
// (D1) RESET
cart.hItems.innerHTML = "";
let item, part, pdt;
let empty = true;
for (let key in cart.items) {
if(cart.items.hasOwnProperty(key)) { empty = false; break; }
}
// (D2) CART IS EMPTY
if (empty) {
item = document.createElement("div");
item.innerHTML = "Cart is empty";
cart.hItems.appendChild(item);
}
// (D3) CART IS NOT EMPTY - LIST ITEMS
else {
let p, total = 0, subtotal = 0;
for (let id in cart.items) {
// ITEM
p = products[id];
item = document.createElement("div");
item.className = "c-item";
cart.hItems.appendChild(item);
// NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "c-name";
item.appendChild(part);
// REMOVE
part = document.createElement("input");
part.type = "button";
part.value = "X";
part.dataset.id = id;
part.className = "c-del cart";
part.addEventListener("click", cart.remove);
item.appendChild(part);
// QUANTITY
part = document.createElement("input");
part.type = "number";
part.value = cart.items[id];
part.dataset.id = id;
part.className = "c-qty";
part.addEventListener("change", cart.change);
item.appendChild(part);
// SUBTOTAL
subtotal = cart.items[id] * p.price;
total += subtotal;
}
// EMPTY BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Empty";
item.addEventListener("click", cart.nuke);
item.className = "c-empty cart";
cart.hItems.appendChild(item);
// CHECKOUT BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Checkout - " + "$" + total;
item.addEventListener("click", cart.checkout);
item.className = "c-checkout cart";
cart.hItems.appendChild(item);
}
},
// (E) ADD ITEM INTO CART
add : function () {
if (cart.items[this.dataset.id] == undefined) {
cart.items[this.dataset.id] = 1;
} else {
cart.items[this.dataset.id]++;
}
cart.save();
cart.list();
},
// (F) CHANGE QUANTITY
change : function () {
if (this.value == 0) {
delete cart.items[this.dataset.id];
} else {
cart.items[this.dataset.id] = this.value;
}
cart.save();
cart.list();
},
// (G) REMOVE ITEM FROM CART
remove : function () {
delete cart.items[this.dataset.id];
cart.save();
cart.list();
},
// (H) CHECKOUT
checkout : function () {
// SEND DATA TO SERVER
// CHECKS
// SEND AN EMAIL
// RECORD TO DATABASE
// PAYMENT
// WHATEVER IS REQUIRED
alert("TO DO");
/*
var data = new FormData();
data.append('cart', JSON.stringify(cart.items));
data.append('products', JSON.stringify(products));
var xhr = new XMLHttpRequest();
xhr.open("POST", "SERVER-SCRIPT");
xhr.onload = function(){ ... };
xhr.send(data);
*/
}
};
window.addEventListener("DOMContentLoaded", cart.init);

Categories