'I want to add items from js generated product table to cart table but I don't how to tell the system what table row am selecting
I'm still trying to find a way to get the addToCart() function to work.
fetch('server.php')
.then((res) => res.json())
.then((response) => {
let output = '';
for (let i in response) {
output += `<tr>
<td>${response[i].quantity}</td>
<td><button>${response[i].productName}</button></td>
<td>₦${response[i].price}.00</td>
<td><button id="go" onclick="addToCart()">+1</button></td>
<td><input type="text"></td>
</tr>`;
}
document.querySelector('.tbody').innerHTML = output;
})
.catch((error) => console.log(error));
function addToCart() {
document.getElementById('fillUp').innerHTML += '<tr><td>123</d></tr>';
console.log(val);
}
<!-- Product Table -->
<table id="myTable">
<thead class="tHeadRow">
<th>Quantity</th>
<th>Products</th>
<th>Price</th>
</thead>
<tbody class="tbody"></tbody>
</table>
<!-- Cart Table -->
<div class="cart">
<h3>Checkout Cart</h3>
<div class="cartContent">
<table class="cartTable">
<tbody id="fillUp"></tbody>
<tfoot>
<tr>
<td style="font-weight: bold">Total:</td>
<td style="font-weight: bold"></td>
</tr>
</tfoot>
</table>
</div>
</div>
<!--- I got a possible solution but when I tried it, I got Uncaught --->
<!--- TypeError: Cannot read properties of null (reading 'rows') --->
var tbody = document.getElementById('tbody'),rIndex;
var tb = tbody.rows.length;
for(var i = 0; i < tb; i++) {
tbody.rows[i].onclick = function() {
console.log(this.cells[0].innerHTML);
}
Solution 1:[1]
Dropping a row into another table was accomplished mainly by cloneNode() and the original row was removed by .remove(). In the OP code:
var tbody = document.getElementById('tbody'),rIndex;
This makes very little sense. There is no tag with an id of #tbody there's a tag with a class of .tbody which at the very least can be accessed by .querySelector() that's why it's null.
The problem will run into as I see it is that you are using an inline event handler:
onclick="addToCart()"
Inline event handlers are garbage. Use on event properties and/or event listeners, read the following after reviewing the example below:
const allTables = document.querySelectorAll('table');
const shop = allTables[0].tBodies[0];
const cart = allTables[1].tBodies[0];
fetch('https://my.api.mockaroo.com/i_mart.json?key=3634fcf0')
.then((res) => res.json())
.then((response) => {
let output = '';
for (let i in response) {
output += `<tr id='R${i}'>
<td><button name='itm' class='itm' type='button'>${response[i].item}</button></td>
<td>?${response[i].price.substring(1)}</td>
<td><input name='qty' class='qty' value='${response[i].quantity}' readonly>
<input name='def' value='${response[i].quantity}' type='hidden'>
</td>
<td><input name='cnt' class='cnt' value='0' readonly><button name="add" class='btn add' type='button' disabled>+1</button>
<button name="sub" class='btn sub' type='button' disabled>-1</button>
</td>
<td><input name='subT' class='subT' value='?0.00' readonly></td>
</tr>`;
}
shop.innerHTML = output;
})
.catch((error) => console.log(error));
const itemTo = (row, dest) => {
const copy = row.cloneNode(true);
row.remove();
dest.appendChild(copy);
const btns = copy.querySelectorAll('.btn');
const fields = copy.querySelectorAll('input');
if (dest === cart) {
btns[0].disabled = false;
} else {
btns.forEach(btn => btn.disabled = true);
fields[0].value = fields[1].value;
fields[2].value = '0';
fields[3].value = '?0.00';
}
};
const addToSubFrom = (row, dir) => {
let D = dir === undefined ? 1 : dir;
const cells = row.children;
let add = row.querySelector('.add');
let sub = row.querySelector('.sub');
let prc = cells[1].textContent.substring(1);
let qty = cells[2].firstElementChild;
let cnt = cells[3].firstElementChild;
let subT = cells[4].firstElementChild;
let c = +cnt.value + D;
if (c === 0) {
sub.disabled = true;
} else {
sub.disabled = false;
}
let q = +qty.value - D;
if (q === 0) {
add.disabled = true;
} else {
add.disabled = false;
}
let p = +prc;
let sT = ((p * 100) * c) / 100;
cnt.value = c;
qty.value = q;
subT.value = '?' + sT.toFixed(2);
};
const getTotal = array => array.map(inp => +inp.value.substring(1) * 100).reduce((sum, cur) => sum + cur);
const addToCart = e => {
const io = e.currentTarget.elements;
const btn = e.target;
if (btn.matches('button')) {
let row = document.querySelector('#' + btn.closest('tr').id);
let S;
switch (btn.name) {
case 'itm':
let dest = btn.closest('tbody').className === 'shop' ? cart : shop;
itemTo(row, dest);
S = [...io.subT];
io.total.value = (getTotal(S) / 100).toFixed(2);
break;
case 'add':
S = [...io.subT];
addToSubFrom(row);
io.total.value = (getTotal(S) / 100).toFixed(2);
break;
case 'sub':
S = [...io.subT];
addToSubFrom(row, -1);
io.total.value = (getTotal(S) / 100).toFixed(2);
break;
default:
break;
}
}
e.stopPropagation();
};
const UI = document.forms[0];
UI.onclick = addToCart;
:root {
font: 1ch/1.5 'Segoe UI'
}
body {
font-size: 3ch;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
caption {
font-size: 2rem;
font-weight: 900
}
.h1 {
width: 35%;
}
.h3 {
width: 20%;
}
.h3 {
width: 10%;
}
.h4 {
width: 20%;
text-align: left;
}
.h5 {
width: 15%;
}
td:nth-of-type(n+2) {
text-align: center;
}
tfoot th {
text-align: right;
}
input,
output {
display: inline-block;
font-size: 100%;
line-height: 1.15;
}
input,
output,
td:nth-of-type(2) {
font-family: Consolas
}
button {
font-size: 1.25rem;
cursor: pointer;
}
output {
font-weight: 900;
}
.qty,
.cnt,
.subT {
width: 2ch;
border: 0;
}
.subT {
width: 6ch
}
<!-- Product Table -->
<form>
<table>
<caption>
iMartâ„¢ Online Wholesale
</caption>
<thead>
<th class='h1'>Item</th>
<th class='h2'>Price</th>
<th class='h3'>Qty</th>
<th class='h4'>Count</th>
<th class='h5'>SubTotal</th>
</thead>
<tbody class='shop'></tbody>
</table>
<!-- Cart Table -->
<table>
<caption>Checkout Cart</caption>
<thead>
<th class='h1'>Item</th>
<th class='h2'>Price</th>
<th class='h3'>Qty</th>
<th class='h4'>Count</th>
<th class='h5'>SubTotal</th>
</thead>
<tbody class='cart'></tbody>
<tfoot>
<tr>
<th colspan='4'>Total: ?</th>
<td><output id='total'></output></td>
</tr>
</tfoot>
</table>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zer00ne |
