How to present data by DOM not by table - javascript

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>

Related

how to create a table and adding data from the array in each <td> of the table?

how to add data from array to the table using javascript ?
var fruits =['apple' ,'orange' , ' grape' , 'banana' , 'guava' , ' watermelon' , 'mango'] ;
showFruits(){
// code here ;
}
you need to create the table inside the function and insert the array data into each cells .
this function is used in a button so when u click it u need to create a table with that array data
check the code comments to better understand what's done step by step
var fruits = ['apple', 'orange', ' grape', 'banana', 'guava', ' watermelon', 'mango'];
showFruits();
function showFruits() {
//1- get the table by specified id
const table = document.getElementById("fruits-table");
//2- loop for each array element
fruits.forEach((fruit, index) => {
//create row (tr)
const tr = document.createElement("tr");
//create index cell (td)
const indexTd = document.createElement("td");
//create fruit cell (td)
const fruitTd = document.createElement("td");
// add index & fruit cells data
indexTd.innerText = index;
fruitTd.innerText = fruit;
// append cells to the row
tr.append(indexTd, fruitTd);
// append the row to the table
table.append(tr);
})
}
table,
td,
th {
border: 1px solid #777;
text-align: center;
}
<table id="fruits-table">
<tr>
<th>Index</th>
<th>Fruit</th>
</tr>
</table>
Done my friend, I use Bootstrap 5 for the table.
In Javascript I used the for loop to go through all the array elements and add them to the table. I defined a counter and pre-incremented it to give us the number of each fruit.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement
Cheers!
//We use const because an array will still be used. In case you want to add/remove elements there are methods for that
const fruits =['apple' ,'orange' , ' grape' , 'banana' , 'guava' , ' watermelon' , 'mango'] ;
function showFruits(){
//define all variables
let count = 0;
let list = '';
let tbodyTable = document.getElementById('fruits');
//Using "for of" to go through all the elements of the array and add them to <td>
//and pre-increment the counter
for(let fruit of fruits){
++count;
list += `
<tr>
<th scope="row" id="counter">${count}</th>
<td>${fruit}</td>
</tr>`
}
tbodyTable.innerHTML = list;
}
//Get the button ID and using addEventListener to show the function
document.getElementById('bot').addEventListener("click", ()=>{
showFruits();
})
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Using Tables with Bootstrap 5</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<h1>Click on button to show Fruits</h1>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Fruits</th>
</tr>
</thead>
<tbody id="fruits">
<tr>
<th scope="row" id="counter"></th>
<td></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary" id="bot">Show fruits</button>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
const table = document.createElement("table");
const tBody = table.createTBody();
const l = fruits.length;
for (let i = 0; i < l; i++) {
tBody.insertRow().insertCell().innerText = fruits[i];
}
yourTableContainer.appendChild(table);

Check for data within a json object in a list

I'm using the JSON API found at https://disease.sh/v3/covid-19/jhucsse. It stores the data as a list of JSON objects. I'm making a small website to allow users to scroll through a list, pick their country and province, and view data for that country/province. I'm using JQuery for this, here is my code so far:
const apiLink = "https://disease.sh/v3/covid-19/jhucsse"
jQuery(document).ready(function() {
jQuery("#SubmitButton").click(function() {
country_value = $('#country_picker').val() //Gets the value of the country_value select list in index.html
$.get(apiLink, function(data,status){
console.log(data[0]) // Placeholder code that prints the first JSON object in the list to the console
// Other code here
})
document.getElementById('output').innerHTML = TestHTML; // Fills the 'output' div element with the output of the program
});
});
How would I approach this problem?
You don't need jQuery. You can use the Fetch API
Get the data as JSON
Since the JSON data is an Array, use the prototype .forEach() method to extract data for each country object
Use .reduce() to construct a HTML string to be appended to the table's TBODY
Use .addEventListener() to attach an "input" Event to your #search input Element
Use the String .includes() method to check if any row has the searched value, and if a value does not matches set the hidden property to that TR element
Here's an example:
const el = (sel, el) => (el || document).querySelector(sel);
const els = (sel, el) => (el || document).querySelectorAll(sel);
const elSearch = el("#search");
const elTable = el("#table");
const elTbody = el("tbody", elTable);
let elsTr;
const apiLink = "https://disease.sh/v3/covid-19/jhucsse";
const row = (item) => `<tr>
<td>${item.country}</td>
<td>${item.province || ""}</td>
<td>${item.county || ""}</td>
<td>${item.stats.confirmed || "-"}</td>
<td>${item.stats.deaths || "-"}</td>
<td>${item.stats.recovered || "-"}</td>
</tr>`;
const build = (data) => {
elTbody.innerHTML = data.reduce((html, item) => html += row(item), "");
elsTr = els("tr", elTbody);
elSearch.addEventListener("input", search);
};
const search = () => {
const value = elSearch.value.trim().toLowerCase();
elsTr.forEach(elTr => {
const content = elTr.textContent.toLowerCase();
const match = content.includes(value);
elTr.hidden = value && !match;
});
};
fetch(apiLink).then(res => res.json()).then(build);
.sticky-thead {
position: relative;
max-height: 140px;
overflow-y: auto;
}
.sticky-thead table {
width: 100%;
border-spacing: 0;
border-collapse: separate;
}
.sticky-thead td,
.sticky-thead th {
text-align: left;
padding: 4px;
}
.sticky-thead thead th {
position: sticky;
top: 0;
background: #fff;
}
<input id="search" type="search" placeholder="Search" autocomplete="off">
<div class="sticky-thead">
<table id="table">
<thead>
<tr>
<th>Country</th>
<th>Province</th>
<th>County</th>
<th>Confirmed</th>
<th>Deaths</th>
<th>Recovered</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
If you want to populate a list, just do a for-loop? data is just an array of objects with properties.
for (let i = 0; i < data.length; i++) {
data[i].country // access the country
data[i].stats.deaths //access the deaths
}

How to show first two rows of a hidden table in another table

I have a table in a hidden modal that populates dynamically anywhere from 0 to 10 rows. I need to get the data from the first two rows of this table to show in another table on my page. Also, if the hidden table has more than 2 rows, it displays a button to show the hidden table. My issue is, my code only works if the hidden table has 2 or more rows. I'm new to javascript and unsure how to correct this...
function populatetable {
// checks for table cell id in the hidden table
var rowcheck = document.getElementById('cell1')
var rowyes = document.getElementById('thetable').contains(rowcheck);
var showbutton = document.getElementById('thebutton');
// when button is still hidden
if (document.getElementById('thetable').getElementsByTagName('tr').length <=2 && rowyes == true) {
// variables for table data in hidden table's first row
var data1 = document.getElementById('td1').innerHTML;
var data2 = document.getElementById('td2').innerHTML;
// variable for table data in hiddent table's second row
var data3 = document.getElementById('td3').innerHTML;
var data4 = document.getElementById('td4').innerHTML;
// populates visible table from rows in hidden table
document.getElementById('vtd1').innerHTML = data1;
document.getElementById('vtd2').innerHTML = data2;
document.getElementById('vtd3').innerHTML = data3;
document.getElementById('vtd4').innerHTML = data4;
}
if else (document.getElementById('thetable').getElementsByTagName('tr').length > 2 && rowyes == true) {
showbutton.style.display = 'block';
var data1 = document.getElementById('td1').innerHTML;
var data2 = document.getElementById('td2').innerHTML;
var data3 = document.getElementById('td3').innerHTML;
var data4 = document.getElementById('td4').innerHTML;
document.getElementById('vtd1').innerHTML = data1;
document.getElementById('vtd2').innerHTML = data2;
document.getElementById('vtd3').innerHTML = data3;
document.getElementById('vtd4').innerHTML = data4;
}
}
This all however, only works if the hidden table only has at least 2 rows. Any ideas?
Consider this school case = we access the elements of an html table by their reference in rows / cells:
(it is also better to use textContent to read their content, if it is only textual)
if you want a identical copy of rows, it should be better to use cloneNode method => https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
const myTab = document.querySelector('#my-table tbody')
console.log( 'lines .....= ', myTab.rows.length )
console.log( 'columns ...= ', myTab.rows[0].cells.length )
console.log( 'table[1,3] = ', myTab.rows[1].cells[3].textContent, '(value)')
table { border-collapse: collapse; margin: 1em }
td { border: 1px solid grey; width: 2em; height: 1em; }
<table id="my-table">
<tbody>
<tr><td>0.0</td><td>0.1</td><td>0.2</td><td>0.3</td><td>0.4</td></tr>
<tr><td>1.0</td><td>1.1</td><td>1.2</td><td>1.3</td><td>1.4</td></tr>
<tr><td>2.0</td><td>2.1</td><td>2.2</td><td>2.3</td><td>2.4</td></tr>
<tr><td>3.0</td><td>3.1</td><td>3.2</td><td>3.3</td><td>3.4</td></tr>
</tbody>
</table>

Populate view with different values in js

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.

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