`appendChild(htmlobject)` only append the last child form an array of data - javascript

I'm making a shopping cart and will load the products of inside the cart after a XMLHttpRequest. Because the complexity of the table rows I've extracted this inside my HTML code (in code below see: #sampleBody). This contains the default markup of the row.
When I've done the request, I take the sampleBody and will append them to the cartBody. This I'll do alter every loop in over data. The problem is that only the first element is visible (I'm looping backwards).
P.S.: In code below I've just add the code what happens after the request.
(function() {
'use strict';
var sampleBody, cartBody;
var data = [{
name: "product 1",
price: 15,
quantity: 2,
total: 30
}, {
name: "name of product 2",
price: 10,
quantity: 3,
total: 30
}]
function init() {
sampleBody = document.getElementById('sampleBody');
cartBody = document.getElementById('cartBody');
}
init();
var renderCart = function(data) {
var html = document.createDocumentFragment();
for (var i = data.length; i--;) {
sampleBody.querySelector('#name').innerText = data[i].name;
sampleBody.querySelector('#price').innerText = data[i].price;
sampleBody.querySelector('#quantity').value = data[i].quantity;
sampleBody.querySelector('#total').innerText = data[i].total;
html.appendChild(sampleBody);
}
while (cartBody.firstChild) {
cartBody.removeChild(cartBody.firstChild);
}
cartBody.appendChild(html);
};
renderCart(data);
})();
.hidden {
display: none;
}
table {
width: 100%;
}
td, th {
border: solid 1px black;
padding: 5px;
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody id="cartBody">
<tr>
<td colspan="4">Loading...</td>
</tr>
</tbody>
</table>
<table class="hidden">
<tr id="sampleBody">
<td id="name"></td>
<td>€<span id="price"></span></td>
<td>
<button>+</button>
<input type="text" id="quantity">
<button>-</button>
</td>
<td>€<span id="total"></span></td>
</tr>
<table>

You have to clone your sampleBody node in your foor loop statement:
for (var i = data.length; i--;) {
var node = sampleBody.cloneNode(true);
node.setAttribute('id', node.getAttribute('id')+i);
node.querySelectorAll('*[id]').forEach(elt =>
elt.setAttribute('id', elt.getAttribute('id')+i)
);
node.querySelector('#name'+i).innerText = data[i].name;
node.querySelector('#price'+i).innerText = data[i].price;
node.querySelector('#quantity'+i).value = data[i].quantity;
node.querySelector('#total'+i).innerText = data[i].total;
html.appendChild(node);
}
We can also remove the ids and replace them by a name attribute:
HTML:
<table class="hidden">
<tr name="sampleBody">
<td name="name"></td>
<td>€<span name="price"></span></td>
<td>
<button>+</button>
<input type="text" name="quantity">
<button>-</button>
</td>
<td>€<span name="total"></span></td>
</tr>
<table>
JS:
...
function init() {
sampleBody = document.querySelector('table.hidden > tr[name="sampleBody"]');
cartBody = document.getElementById('cartBody');
}
...
for (var i = data.length; i--;) {
var node = sampleBody.cloneNode(true);
node.querySelector('*[name="name"]').innerText = data[i].name;
node.querySelector('*[name="price"]').innerText = data[i].price;
node.querySelector('*[name="quantity"]').value = data[i].quantity;
node.querySelector('*[name="total"]').innerText = data[i].total;
html.appendChild(node);
}

The issue is that id attribute values should be unique in valid HTML. So you should not use id for what you are doing. You can use class for this instead, and then filter for the one you want to assign the text to, like this:
for (var i = data.length; i--;) {
sampleBody.querySelectorAll('.name')[i].innerText = data[i].name;
sampleBody.querySelectorAll('.price')[i].innerText = data[i].price;
sampleBody.querySelectorAll('.quantity')[i].value = data[i].quantity;
sampleBody.querySelectorAll('.total')[i].innerText = data[i].total;
html.appendChild(sampleBody);
}
It would in fact be more efficient to perform those 4 querySelectorAll once, before the loop:
var names = sampleBody.querySelectorAll('.name');
var prices = sampleBody.querySelectorAll('.price');
var quantities = sampleBody.querySelectorAll('.quantity');
var totals = sampleBody.querySelectorAll('.total');
for (var i = data.length; i--;) {
names[i].innerText = data[i].name;
prices[i].innerText = data[i].price;
quantities[i].value = data[i].quantity;
totals[i].innerText = data[i].total;
html.appendChild(sampleBody);
}

Related

For loop inside for loop not working properly repeating same values multiple times Javascript

I'm wanting every <tbody> tag will be gone as object index like first <tbody>->1 and second <tbody>-> 2 then inside the <tbody> every <tr> will be another object and that will be store into the <tbody> object and last the last part every <td> should have object key ("eiin", "name") inside the <tr> object
I'm trying using for loop multiple times but the console.log showing me okay but first object repeated 2 times.
Html
<section class="institute_list">
<table class="table" border="1">
<thead>
<tr>
<th scope="col">EIIN</th>
<th scope="col">Institute</th>
</tr>
</thead>
<tbody>
<tr>
<td>000000</td>
<td>Name</td>
</tr>
</tbody>
<tbody>
<tr>
<td>111111</td>
<td>Name 2</td>
</tr>
</tbody>
</table>
</section>
Javascript & jQuery
<script>
var rows = '', the_row='', the_xrow={}, tr_values={}, xtd_obj={};
tbodys = ($(".institute_list .table tbody").length);
for( var x=0; tbodys > x; x++) {
rows = $('.institute_list .table tbody:nth-child('+(x+1)+') tr').length;
the_row = '.institute_list .table tbody:nth-child('+(x+1)+') tr:nth-child(';
for( var i=1; rows >= i; i++ ){
tr_values = {
'eiin' : $(the_row+i+') td:first-child').text(),
'name' : $(the_row+i+') td:nth-child(2)').text()
};
the_xrow[i] = tr_values;
}
xtd_obj[x] = the_xrow;
}
console.log(xtd_obj);
</script>
and i'm getting this output in console
here
You may try the code below. You can separate every <tbody>,<tr>,<td> tag as a loop then make them a array.
var target = $(".institute_list > table");
var output = [];
$(target).find("tbody").each(function(i){
output[i] = {};
$(this).children().each(function(j){
output[i][j] = {};
$(this).children().each(function(k, td){
if ( k == 0 ) {
output[i][j]["eiin"] = $(td).text();
} else if ( k == 1 ) {
output[i][j]["name"] = $(td).text();
} else {
output[i][j][k] = $(td).text();
}
});
});
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="institute_list">
<table class="table" border="1">
<thead>
<tr>
<th scope="col">EIIN</th>
<th scope="col">Institute</th>
</tr>
</thead>
<tbody>
<tr>
<td>000000</td>
<td>Name</td>
</tr>
</tbody>
<tbody>
<tr>
<td>111111</td>
<td>Name 2</td>
</tr>
</tbody>
</table>
</section>
First, you need a closing </tbody> tag around the first element. Second I think you might be running into a scoping problem. You are defining the_xrow and tr_values outside of the for loops instead of inside of the for loops.
<script>
var xtd_obj={};
var tbodys = ($(".institute_list .table tbody").length);
for( var x=1; tbodys >= x; x++) {
var current_row = '.institute_list .table tbody:nth-child('+x+') tr';
var rows = $(current_row).length;
var the_row = current_row + ':nth-child(';
var the_xrow = {};
for( var i=1; rows >= i; i++ ){
the_xrow[i] = {
'eiin' : $(the_row+i+') td:first-child').text(),
'name' : $(the_row+i+') td:nth-child(2)').text()
};
}
xtd_obj[x] = the_xrow;
}
console.log(xtd_obj);
</script>
It's working for me
<script>
var rows = '', the_row='', xtd_obj={};
var tbodys = ($(".institute_list .table tbody").length)+1;
for( var x=1; tbodys > x; x++) {
rows = $('.institute_list .table tbody:nth-child('+(x+1)+') tr').length;
the_row = '.institute_list .table tbody:nth-child('+(x+1)+') tr:nth-child(';
var the_xrow = {};
for( var i=0; rows > i; i++ ){
var tr_values = {
'eiin' : $(the_row+i+1+') td:first-child').text(),
'name' : $(the_row+i+1+') td:nth-child(2)').text()
};
the_xrow[i] = tr_values;
}
xtd_obj[x] = the_xrow;
}
console.log(xtd_obj);
</script>
Here's the screenshot

Creating HTML table based on values

I have an html table that I want to read from and create a new table underneath it from reading the first table. The first table looks like this:
ID | Value
100 | 3
200 | 2
400 | 7
100 | 4
and should output this
ID | Total
100 | 7
200 | 2
400 | 7
I'm having trouble creating the new rows after the first row and adding them based on ID, heres what I have so far
var id = document.getElementByID("total");
var td = document.createElement('td');
var eleName = document.getElementsByName('initValue');
var total = 0;
for (var i = 1; i < eleName.length; i++) {
total += parseInt(eleName[i].value);
}
td.textContent = total;
id.appendChild(td);
Right now its just adding all the values
The ID can only increase by 100 and can have more than just 100-400 and more entries. The inital table is made with php
original table html
<table>
<tr><th>ID</th><th>Value</th></tr>
<tr><td name="itin" id="itin">100</td><td id="initValue" name="initValue">3</td></tr>
<tr><td name="itin" id="itin">200</td><td id="initValue" name="initValue">2</td></tr>
<tr><td name="itin" id="itin">400</td><td id="initValue"name="initValue">7</td></tr>
<tr><td name="itin" id="itin">100</td><td id="initValue" name="initValue">4</td></tr>
</table>
As a few people have said in the comments an element's ID, <el id="something">, must be unique and there cannot be any duplicates of it on the page. If you want to "group" similar elements use a class.
For solving your problem, since the value of your ID is is a direct sibling we only need one selector to get the ID and Value:
const itin = document.querySelectorAll('[name="itin"]');
With this we can loop over every ID element, name="itin", and get the value with el.nextElementSibling.textContent. We're going to be keeping track of our IDs and Values in an object since javascript doesn't have key/value pair arrays: let values = {}.
We use .nextElementSibling to ignore white spaces and only get the next element.
We check if values already has a record of our ID with hasOwnProperty, if it does, we add the values together, if not we create a property in values with our ID and give it a value:
if (values.hasOwnProperty(inner)) {
values[inner] = values[inner] += parseInt(next);
} else {
values[inner] = parseInt(next);
}
Next we create a second loop to iterate over all properties in values and build our new table with that and the rest is pretty straight forward.
The two loops could likely be combined into one with a bit more logic to search for matching IDs.
const itin = document.querySelectorAll('[name="itin"]');
let values = {};
itin.forEach(item => {
const inner = item.textContent;
let next = null;
/* For direct sibling use this */
//const next = item.nextElementSibling.textContent;
/* For an unknown sibling use this */
for ( let a = 0; a < item.parentElement.children.length; a++ ) {
const n = item.parentElement.children[a];
if ( n.getAttribute('name') === 'initValue') {
next = n;
}
}
next = next.textContent;
/****/
if (values.hasOwnProperty(inner)) {
values[inner] = values[inner] += parseInt(next);
} else {
values[inner] = parseInt(next);
}
});
const table_two = document.querySelector('.table-two tbody');
for (let prop in values) {
const val = values[prop];
let tr = document.createElement('tr');
let td1 = document.createElement('td');
let td2 = document.createElement('td');
td1.innerHTML = prop;
td2.innerHTML = val;
tr.appendChild(td1);
tr.appendChild(td2);
table_two.appendChild(tr);
}
<table>
<tr>
<th>ID</th>
<th>Value</th>
</tr>
<tr>
<td name="itin">100</td>
<td name="initValue">3</td>
</tr>
<tr>
<td name="itin">200</td>
<td name="initValue">2</td>
</tr>
<tr>
<td name="itin">400</td>
<td name="initValue">7</td>
</tr>
<tr>
<td name="itin">100</td>
<td name="initValue">4</td>
</tr>
</table>
<table class="table-two">
<thead>
<tr>
<th>ID</th>
<th>Value</th>
</tr>
</thead>
<tbody></tbody>
</table>
An entirely javascript solution based on what you have provided is available on this jsfiddle
var tds = document.getElementsByName("itin");
var tdDict = {};
var keys = [];
for(var i=0;i<tds.length;i++){
var tdId = tds[i];
var tdVal = tds[i].nextSibling;
if(tdId.textContent in tdDict){
var curTotal = tdDict[tdId.textContent];
var newTotal = curTotal + parseInt(tdVal.textContent);
tdDict[tdId.textContent] = newTotal;
}
else{
tdDict[tdId.textContent] = parseInt(tdVal.textContent);
keys.push(tdId.textContent);
}
}
var totalDiv = document.getElementById("totals");
var totalTable = document.createElement("table");
totalDiv.append(totalTable);
var hrow = document.createElement("tr");
var idHeader = document.createElement("th");
idHeader.textContent = "ID";
var totalHeader = document.createElement("th");
totalHeader.textContent = "Total";
totalTable.append(hrow);
hrow.append(idHeader);
hrow.append(totalHeader);
for(var i=0;i<keys.length; i++){
var newRow = document.createElement("tr");
var idVal = keys[i];
var valVal = tdDict[idVal];
var idValTd = document.createElement("td");
idValTd.textContent = idVal;
var valValTd = document.createElement("td");
valValTd.textContent = valVal;
newRow.appendChild(idValTd);
newRow.appendChild(valValTd);
totalTable.appendChild(newRow);
}
<table>
<tr><th>ID</th><th>Value</th></tr>
<tr><td name="itin" id="itin">100</td><td id="initValue" name="initValue">3</td></tr>
<tr><td name="itin" id="itin">200</td><td id="initValue" name="initValue">2</td></tr>
<tr><td name="itin" id="itin">400</td><td id="initValue"name="initValue">7</td></tr>
<tr><td name="itin" id="itin">100</td><td id="initValue" name="initValue">4</td></tr>
</table>
<div id="totals">
</div>

Getting the values from textfield to save as PDF

I already can retrieve every values on my cell depending on what the user input. Using this.
$("#customFields > tbody tr > td").each(function()
{
console.log($(this).find("input").val());
});
But I'm just having a little problem on how can I append user input in the textfield? Becasue when I save as a pdf I got a crumpled <input type="text" class="form-control"> in one cell and it's not getting the values that I input. Screenshot below.
Screenshot:
Is there a way how can I input that values that I inserted here in every cell? I'm stuck in this part I need opinion from others how can I do this.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-primary" id = "save">Save</button>
</div>
Script:
$("#customFields > tbody tr > td").each(function() {
console.log($(this).find("input").val());
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF() {
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1', 'pt', 'letter', true);
doc.cellInitialize();
$.each(table, function(i, row) {
$.each(row, function(j, cell) {
doc.cell(1, 10, 90, 20, cell, i);
});
});
doc.save('text.pdf');
}
javascript: genPDF();
Replace your source code to:
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].children[0].value;
alert(rowData[headers[j]]);
}
This is my test
Hope this can help you. xD

Compare participants in one column of the table and make sum from other column, js

I have a table. I'd like to compare participants. If participant have several result points in the table, the script has to return sum of all participant's results. And so on for every participant.
The table is generated from database (".$row["pnt"]."".$row["station"]."".$row["res"]."):
Participant Station Points
aa Some1 1
dd Some1 2
aa sm2 3
dd sm2 4
bb sm3 5
ee sm3 6
For example I've to recieve such a new table:
aa - 4,
dd - 6,
bb - 5,
ee - 6
I've tried to do so:
$(document).ready(function () {
$("body").click(function () {
var rows = $("tbody tr");
var jo = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j <= rows.length; j++) {
var pnt1 = $(rows[i]).find(".pnt").html();
var stations1 = $(rows[i]).find(".station").html();
var pntR1 = $(rows[i]).find(".res").html();
if (pnt1 == $(rows[j]).find(".pnt").html()) {
pntR1 = parseInt(pntR1);
pntR2 = parseInt($(rows[j]).find(".res").html());
jo.push(pnt1, pntR1, pntR2);
break;
}
}
}
console.log(jo);
});
});
But I understood that I'm on a wrong way. Please, help me. I really appreicate if some one could help me on this issue.
Updated after comments:
<table id="pntsRes">
<thead>
<tr>
<th>Участники</th>
<th>Баллы</th>
</tr>
</thead>
<tbody>
<tr><td class="pnt">aa</td><td class="station">AES</td><td class="res">1</td></tr><tr><td class="pnt">dd</td><td class="station">AES</td><td class="res">2</td></tr>
<tr><td class="pnt">aa</td><td class="station">Science</td><td class="res">3</td></tr>
<tr><td class="pnt">dd</td><td class="station">Science</td><td class="res">4</td></tr><tr><td class="pnt">bb</td><td class="station">Аэродром</td><td class="res">5</td></tr>
<tr><td class="pnt">ee</td><td class="station">aeroport</td><td class="res">6</td></tr></tbody>
</table>
First, I would consider breaking your solution into three functions - one to extract the data from the HTML (which is a questionable practice in itself), one to transform the data, and one to output the new table. This way, your code is much more maintainable.
function getData() {
var rows = $("tbody tr");
var data = [];
rows.each(function(idx, row){
var pnt = row.find('.pnt').html(),
station = row.find('.station').html()),
res = parseInt(row.find('.res').html());
data.push(pnt, station, res);
});
}
Then I would consider something like this for the second method
// Pass the output from getData() into processData()
function processData(data){
var groupedKeys = {};
var groupedData = data.map(function(datum){
var name = datum[0];
var value = datum[2];
groupedKeys[name] = (groupedKeys[name] || 0) + (value || 0);
});
var transformedData = [];
Object.keys(groupedKeys).forEach(function(key){
transformedData.push([key, groupedKeys[key]]);
});
return transformedData;
}
The last method of course would need to be implemented by yourself, there's a ton that could be improved here, but it could be a good start.
I used an associative array (which is just an object in JavaScript) shown below:
http://jsfiddle.net/a5k6w300/
Changes I made:
var jo = [];
changed to an object instead of an array
var jo = {};
I also added the if(isNaN(object[key]) inside the inner loop in order to make sure that these didn't show as NaN as I continued adding them together.
$(document).ready(function () {
$("body").click(function () {
var rows = $("tbody tr");
var jo = {};
console.log(rows);
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j <= rows.length; j++) {
var pnt1 = $(rows[i]).find(".pnt").html();
var stations1 = $(rows[i]).find(".station").html();
var pntR1 = $(rows[i]).find(".res").html();
if (pnt1 == $(rows[j]).find(".pnt").html()) {
pntR1 = parseInt(pntR1);
pntR2 = parseInt($(rows[j]).find(".res").html());
if(isNaN(jo[pnt1])){
jo[pnt1] = 0;
}
jo[pnt1] += pntR1;
break;
}
}
}
console.log(jo);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="pntsRes">
<thead>
<tr>
<th>Участники</th>
<th>Баллы</th>
</tr>
</thead>
<tbody>
<tr>
<td class="pnt">aa</td>
<td class="station">AES</td>
<td class="res">1</td>
</tr>
<tr>
<td class="pnt">dd</td>
<td class="station">AES</td>
<td class="res">2</td>
</tr>
<tr>
<td class="pnt">aa</td>
<td class="station">Science</td>
<td class="res">3</td>
</tr>
<tr>
<td class="pnt">dd</td>
<td class="station">Science</td>
<td class="res">4</td>
</tr>
<tr>
<td class="pnt">bb</td>
<td class="station">Аэродром</td>
<td class="res">5</td>
</tr>
<tr>
<td class="pnt">ee</td>
<td class="station">aeroport</td>
<td class="res">6</td>
</tr>
</tbody>
</table>

Loop through html cells and perform a function if conditionals are met

var tableBody = document.getElementById("firstTableBody"),
secondTable = document.getElementById("secondTable");
function insertRow() {
var Row = tableBody.insertRow();
for (var c = 0; c < 3; c += 1) {
Row.insertCell(c);
}
var Fruits = ["Apples", "Oranges", "Strawberries"],
random_Fruits = Fruits[Math.floor(Math.random() * Fruits.length)];
Row.cells[0].innerHTML = random_Fruits;
Row.cells[1].innerHTML = 100;
var Sellbtn = document.createElement('button');
Sellbtn.innerHTML = "Sell"
Sellbtn.onclick = function Sell() {
if (secondTable.rows.length < 1) {
var Row = secondTable.insertRow();
for (var f = 0; f < 2; f += 1) {
Row.insertCell(f);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
} else {
for (var i = 0; i < secondTable.rows.length; i += 1) {
if (secondTable.rows[i].cells[0].innerHTML === this.parentNode.parentNode.cells[0].innerHTML) {
secondTable.rows[i].cells[1].innerHTML = +this.parentNode.parentNode.cells[1].innerHTML;
} else {
var Rowz = secondTable.insertRow();
for (var k = 0; k < 4; k += 1) {
Rowz.insertCell(k);
}
Rowz.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Rowz.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
}
}
}
}
Row.cells[2].appendChild(Sellbtn);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
<th>
<button onclick="insertRow()">Insert</button>
</th>
</thead>
<tbody id="firstTableBody">
</tbody>
</table>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTable">
</tbody>
</table>
</body>
I insert a row with randomly inserted fruit name and a dynamically added button called sell. When I click on sell it should check if the fruit name of that row exists in the second table or not if so then it should add the sold amount in the row that's in the second table that has the same name. If not then simply add a new row in the second table with the name and sold amount. jQuery is ok.
here is a possible solution, replacement for your function Sell()
Sellbtn.onclick = function Sell() {
var found = false,
rows = secondTable.rows,
numrows = rows.length,
tofind = this.parentNode.parentNode.cells[0].innerHTML,
foundin,
numToAdd = parseInt(this.parentNode.parentNode.cells[1].innerHTML),
num,
x;
for(x=0;x<numrows;x++){
if(rows[x].cells[0].innerHTML === tofind){
found = true;
foundin = x;
}
}
if(found){
num = parseInt(rows[foundin].cells[1].innerHTML) + numToAdd;
rows[foundin].cells[1].innerHTML = num;
}
else{
var Row = secondTable.insertRow();
for (var f = 0; f < 2; f += 1) {
Row.insertCell(f);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
}
}
is this what you're looking for?
$(document).ready(function() {
$('.insert').on('click', function() {
var Fruits = ["Apples", "Oranges", "Strawberries"];
var random_Fruit = Fruits[Math.floor(Math.random() * Fruits.length)];
var clone = $('#template').clone(true).attr('id', '');
clone.css('display', '');
clone.closest('tr').find('.item').html(random_Fruit);
clone.appendTo('#firstTableBody');
});
$('#firstTableBody').on('click', '.sell', function(e) {
e.preventDefault();
var item = $(this).closest('tr').find('.item').html();
var add = parseInt($(this).closest('tr').find('.number').html());
var inTable2 = [];
$('#secondTable tr').each(function() {
var fruit = $(this).find('.item').html();
inTable2.push(fruit);
});
console.log(inTable2);
if ($.inArray(item, inTable2) > -1) {
console.log('in array');
$('#secondTable tr').each(function() {
var fruitIn2 = $(this).find('.item').html();
if (fruitIn2 == item) {
var sold = parseInt($(this).find('.number').html());
$(this).find('.number').html(sold + add);
}
});
}
else {
console.log('add');
var clone = $('#template').clone(true).attr('id', '');
clone.css('display', '');
clone.closest('tr').find('.item').html(item);
clone.closest('tr').find('.sellTd').remove();
clone.appendTo('#secondTable');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
<thead>
<th>Item</th>
<th>Number</th>
<th>
<button class="insert">Insert</button>
</th>
</thead>
<tbody id="firstTableBody">
<tr id="template" class="fruit" style="display:none;">
<td class="item"></td>
<td class="number">100</td>
<td class="sellTd"><button class="sell">Sell</button></td>
</tr>
</tbody>
</table>
<br/><br/>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTable">
</tbody>
</table>
sorry i kinda used all jquery cause it makes it simpler for me to code in and think xp but it works :D

Categories