Updating row ID when swapping HTML table rows - javascript

I've been messing with manipulating HTML tables for the past few weeks and I've come across a problem I am not sure how to fix. So the collection of rows for a table can be iterated over like an array, but if you've switched out the rows a lot, won't the IDs be mixed and doesn't the browser rely on the IDs as the way to iterate over the row objects? I'm running into a problem (probably due to a lack of understanding) where the rows eventually stop moving or one row gets duplicated on top of another. Should I somehow be updating the row's ID each time it is moved? Here is my source so far for this function.
function swap(rOne, rTwo, tblID) {
tblID.rows[rOne].setAttribute('style', 'background-color:#FFFFFF');
var tBody = tblID.children[0];
var rowOne;
var rowTwo;
if (rOne > rTwo) {
rowOne = rOne;
rowTwo = rTwo;
}
else {
rowOne = rTwo;
rowTwo = rOne;
}
var swapTempOne = tblID.rows[rowOne].cloneNode(true);
var swapTempTwo = tblID.rows[rowTwo].cloneNode(true);
hiddenTable.appendChild(swapTempOne);
hiddenTable.appendChild(swapTempTwo);
tblID.deleteRow(rowOne);
var rowOneInsert = tblID.insertRow(rowOne);
var rowOneCellZero = rowOneInsert.insertCell(0);
var rowOneCellOne = rowOneInsert.insertCell(1);
var rowOneCellTwo = rowOneInsert.insertCell(2);
var rowOneCellThree = rowOneInsert.insertCell(3);
rowOneCellZero.innerHTML = hiddenTable.rows[2].cells[0].innerHTML;
rowOneCellOne.innerHTML = hiddenTable.rows[2].cells[1].innerHTML;
rowOneCellTwo.innerHTML = hiddenTable.rows[2].cells[2].innerHTML;
rowOneCellThree.innerHTML = hiddenTable.rows[2].cells[3].innerHTML;
tblID.deleteRow(rowTwo);
var rowTwoInsert = tblID.insertRow(rowTwo);
var rowTwoCellZero = rowTwoInsert.insertCell(0);
var rowTwoCellOne = rowTwoInsert.insertCell(1);
var rowTwoCellTwo = rowTwoInsert.insertCell(2);
var rowTwoCellThree = rowTwoInsert.insertCell(3);
rowTwoCellZero.innerHTML = hiddenTable.rows[1].cells[0].innerHTML;
rowTwoCellOne.innerHTML = hiddenTable.rows[1].cells[1].innerHTML;
rowTwoCellTwo.innerHTML = hiddenTable.rows[1].cells[2].innerHTML;
rowTwoCellThree.innerHTML = hiddenTable.rows[1].cells[3].innerHTML;
tblID.rows[rowOne].setAttribute('onclick', 'chkThis(event, this)');
tblID.rows[rowTwo].setAttribute('onclick', 'chkThis(event, this)');
for (iHiddenDelete = 2; iHiddenDelete >= 1; iHiddenDelete--) {
hiddenTable.deleteRow(iHiddenDelete);
}
}
EDIT: Adding HTML for page and the function for moving between tables which I suspect is causing the issue.
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
FUNCTION STARTS HERE
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var cln = row.cloneNode(true);
toTbl.appendChild(cln);
frTbl.deleteRow(num);
}
sum();
}

So it turns out that my row cloning for moving between tables was causing malformed HTML where the rows would not longer be inside the table body tags. In addition, not trusting the browser to keep track of the button IDs and using the button IDs to setAttributes to the button also caused button ID overlap eventually. So, I got rid of the node cloning and did the row moving between tables the manual way and used innerHTML to add the function call inside the buttons. Upon further reflection, I've come to learn that some people actually make functions that handle ALL button clicks without calling them inside the button and route them to the proper function depending on the ID or other factors such as parent nodes of the button. Perhaps that is best. The main trick here is to STICK TO ONE METHOD. I was all over the place in how I manipulated the tables and it broke things. Here is the working source for those looking to do similar things.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style type="text/css">
#selectSource {
width: 320px;
}
#selectTarget {
width: 320px;
}
table, th, td
{
border: 1px solid black;
}
</style>
<title>Loader</title>
<script>
var chkArray = [];
var data = [];
var tmpArray = [];
var iChk = 0;
var swap;
window.onload = function () {
var load = document.getElementById('selectSource')
loadFromAJAX();
}
function loadFromAJAX()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var rawData = xmlhttp.responseText;
data = JSON.parse(rawData);
for (iData = 0; iData < data.length; iData++) {
newRow = document.getElementById('tblSource').insertRow(iData + 1);
var dn = "dn" + (iData + 1);
var up = "up" + (iData + 1);
cel0 = newRow.insertCell(0);
cel1 = newRow.insertCell(1);
cel2 = newRow.insertCell(2);
cel3 = newRow.insertCell(3);
cel4 = newRow.insertCell(4);
cel0.innerHTML = "<input type='checkbox' name='chkbox'>";
cel1.innerHTML = data[iData].num;
cel2.innerHTML = data[iData].cube;
cel3.innerHTML = data[iData].wgt;
cel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
}
}
}
xmlhttp.open("POST","http://192.168.3.2/cgi-bin/rims50.cgi/json.p",true);
xmlhttp.send();
}
function moveUp(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowIndex = mvThisRowRow.rowIndex;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex - 1;
var mvThisDn = "dn" + (mvToRow) + mvThisRowTbl;
var mvThisUp = "up" + (mvToRow) + mvThisRowTbl;
if (mvThisRowIndex - 1 !== 0) {
moveToRow = mvThisRowTbl.insertRow(mvToRow);
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex +1);
}
else {
alert("You can't move the top row 'up' try moving it 'down'.");
}
}
function moveDn(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvThisRowIndex = mvThisRowRow.rowIndex;
if (mvThisRowIndex + 1 !== mvThisRowTblLngth) {
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex + 2;
var moveToRow = mvThisRowTbl.insertRow(mvToRow);
var dn = "dn" + (mvToRow) + mvThisRowTbl;
var up = "up" + (mvToRow) + mvThisRowTbl;
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex);
}
else {
alert("You can't move the bottom row 'down' try moving it 'up'.");
}
}
function sum() {
var trgTbl = document.getElementById('tblTarget');
var tblLength = trgTbl.rows.length;
var sumAddCube = 0;
var sumAddWgt = 0;
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
for (iSum = 1; iSum < tblLength; iSum++) {
celCubeNum = trgTbl.rows[iSum].cells[2].innerHTML;
celWgtNum = trgTbl.rows[iSum].cells[3].innerHTML;
sumAddCube = parseInt(sumAddCube) + parseInt(celCubeNum);
sumAddWgt = parseInt(sumAddWgt) + parseInt(celWgtNum);
}
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
}
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var toRow = toTbl.rows.length
moveRow = toTbl.insertRow(toRow);
var dn = "dn" + (toRow) + toTbl;
var up = "up" + (toRow) + toTbl;
mvCel0 = moveRow.insertCell(0);
mvCel1 = moveRow.insertCell(1);
mvCel2 = moveRow.insertCell(2);
mvCel3 = moveRow.insertCell(3);
mvCel4 = moveRow.insertCell(4);
mvCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvCel1.innerHTML = row.cells[1].innerHTML;
mvCel2.innerHTML = row.cells[2].innerHTML;
mvCel3.innerHTML = row.cells[3].innerHTML;
mvCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
frTbl.deleteRow(num);
}
sum();
}
</script>
</head>
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

Related

Html table add column with javascript

I am obviously very new to JS. I need to solve a problem where i can't change the HTML and CSS-file. From the HTML-file I am supposed to:
add a column with the header "Sum". (Already did that)
add a row att the bottom with the div id "sumrow". (Did that as well)
add a button at the end. (Did that)
add the total from columns "Price and Amount" into column "Sum" when button is clicked
(This where I am lost)
And like I said I can't change anything in HTML and CSS-files.
// Create a newelement and store it in a variable
var newEl = document.createElement('th');
//Create a text node and store it in a variable
var newText = document.createTextNode('Summa');
//Attach the newtext node to the newelement
newEl.appendChild(newText);
//Find the position where the new element should be added
var position = document.getElementsByTagName('tr')[0];
//Insert the newelement into its position
position.appendChild(newEl);
// Find a <table> element with id="myTable":
var table = document.getElementById("pricetable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(-1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
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);
// Add some text to the new cells:
cell1.innerHTML = "";
cell2.innerHTML = "";
cell3.innerHTML = "";
cell4.innerHTML = sumVal;
cell5.innerHTML = "";
cell6.innerHTML = "";
//Puts divid sumrow
row.setAttribute("id", "sumrow");
var table = document.getElementById("pricetable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
//Creates button
var button = document.createElement("button");
button.innerHTML = "Beräkna pris";
// 2. Append somewhere
var body = document.getElementsByTagName("tbody")[0];
body.appendChild(button);
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
button.setAttribute("class", "btn-primary");
function medelVarde(celler){
var summa = 0;
for(var i = 3; i < celler.length -1; i++){ //Räknar igenom från cell nr 4
var nuvarandeVarde = celler[i].firstChild.nodeValue;
summa = summa + parseInt(nuvarandeVarde);
}
var medel = summa / 1;
return medel;
}
function raknaUtMedelvarde(){
var tabell = document.getElementById("pricetable");
var rader = tabell.getElementsByTagName("tr");
for(var i = 1; i < rader.length; i++){
var tabellceller = rader[i].getElementsByTagName("td"); //Pekar på de td-element som vi har hämtat
var medel = medelVarde(tabellceller);
var medeltext = document.createTextNode(medel);
var medelelement = tabellceller[tabellceller.length - 1];
var row2 = table.insertRow(-1);
medelelement.appendChild(medeltext.cloneNode(true));
.table {
background: white;
}
tr#sumrow {
background-color: #cce4ff;
}
tr#sumrow td:first-child::after{
content: "\a0";
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Handling calculations and tables</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="container">
<div id="header" class="text-center px-3 py-3 pt-md-5 pb-md-4 mx-auto">
<h1 class="display-4">Home Electronics</h1>
<p class="lead">Excellent prices on our hone electronics</p>
</div>
<div id="content">
<table id="pricetable" class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Articlenr</th>
<th>Producttype</th>
<th>Brand</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Telephone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>22256289</td>
<td>Telephone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>24444343</td>
<td>Telephone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- add this script as snippet in this question -->
<!-- <script src="scripts/calculate.js"></script> -->
</body>
</html>
Or code is available on https://jsfiddle.net/cmyr2fp6/
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
For the button click event listener, you don't have to add the medelVarde function.
Also, speaking of that function, I'm not really sure what's happening there. Are you trying to multiply the price and the amount? If so, you can just get the price cell's text and multiply it by the amount input's value (converting to Number the values before multiplying).
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
The [,,, priceCell, amountCell, sumCell] is just a short-hand for getting the cells you want from the row (destructuring assignment. querySelectorAll returns a NodeList wherein you can get the element by index.
function setUp() {
// Set up table.
const table = document.getElementById('pricetable');
const headerRow = table.querySelector('thead tr');
const sumHeader = headerRow.insertCell();
const tbody = table.querySelector('tbody');
const sumTotalRow = tbody.insertRow();
const sumTotalCell = sumTotalRow.insertCell();
sumHeader.innerText = 'Summa';
sumTotalCell.colSpan = '5';
sumTotalCell.innerText = 'Total';
tbody.querySelectorAll('tr').forEach(row => row.insertCell());
// Set up button.
const btn = document.createElement('button');
btn.innerText = 'Beräkna pris';
btn.addEventListener('click', () => {
let total = 0;
tbody.querySelectorAll('tr').forEach((row, i, arr) => {
if (i < arr.length - 1) {
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
sumCell.innerText = sum;
total += sum;
} else {
const totalCell = row.querySelector('td:last-child');
totalCell.innerText = total;
}
});
});
document.body.appendChild(btn);
}
setUp();
Hey ZioPaperone welcome to the JS World :-)
First of all I would recommend to wrap you logic into functions, eg
appendRow() {
//put append row logic here
}
Now let's move on to your question, appending a column is a bit more of a trick then appending a row. You might noticed already that the DOM-Structure is a bit more complex. So for a row you could you correctly has added a node to your tbody.
For a column we need to learn how to create a cell and how we add an entry to the thead. We will use the insertCell() method to insert cells, for thead cells that won't work, so we need to add the th with createElement() and append it with appendChild()
function appendColumn() {
// insertCell doesn't work for <th>-Nodes :-(
var tableHeadRef = document.getElementById('pricetable').tHead; // table reference
var newTh = document.createElement('th');
tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead
newTh.innerHTML = 'thead title';
// open loop for each row in tbody and append cell at the end
var tableBodyRef = document.getElementById('pricetable').tBodies[0];
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var newCell = tableBodyRef.rows[i].insertCell(-1);
newCell.innerHTML = 'cell text'
}
}
EDIT:
To sum up values in col u can use the same approach. I broke down the nodes for better understanding. You also might want to add a check if your table data contains a number with isNaN().
function sumColumn(tableId, columnIndex) {
var tableBodyRef = document.getElementById(tableId).tBodies[0];
var sum = 0; // Initialize sum counter with 0
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var currentRow = tableBodyRef.rows[i]; //access current row
var currentCell = currentRow.cells[columnIndex]; // look for the right column
var currentData = currentCell.innerHTML; // grab cells content
var sum += parseFloat(currentData); // parse content and add to sum
}
return sum;
}

How to insert a new row using JS HTML DOM?

However, the problem is upon clicking again the add button, columns are being created on the same row instead of a new row is created. Can somebody help me regarding to my problem?
var id = 0;
tblStudent = document.getElementById("tblStudent");
function insertValue() {
id++;
var txtFirstName = document.getElementById("txtFirstName").value;
var txtLastName = document.getElementById("txtLastName").value;
var td = document.createElement("td");
var tdValue = document.createTextNode(id);
if(id != "") {
td.appendChild(tdValue);
tblStudent.insertBefore(td, tblStudent.lastChild);
var td = document.createElement("td");
var tdValue = document.createTextNode(txtFirstName);
if(txtFirstName != "") {
td.appendChild(tdValue);
tblStudent.insertBefore(td, tblStudent.lastChild);
var td = document.createElement("td");
var tdValue = document.createTextNode(txtLastName);
if(txtLastName != "") {
td.appendChild(tdValue);
tblStudent.insertBefore(td, tblStudent.lastChild);
}
}
}
}
<input type="text" id="txtFirstName"><br><br>
<input type="text" id="txtLastName"><br><br>
<button onclick= "insertValue()">Add</button>
<table border = "1px">
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<tbody id = "tblStudent">
</tbody>
</table>

Javascript Dynamic Accordion Help needed

I have my mock up here https://codepen.io/anon/pen/WzMpga?editors=0010
I need help in making the last column as clickable button and on the click(action), the hierarchy of the employee should expand in the first column.
Also, if you could guide me how to get the that +/- icon on the button click if it has a parent
function createAccordion(oneEmployee) {
var returnValues = [];
var accordionButton = document.createElement("button");
accordionButton.className = "accordion";
accordionButton.setAttribute("value", oneEmployee.resolverGroups);
accordionButton.setAttribute("onClick", "populateResolverGroups('"+oneEmployee.resolverGroups+"', '" + oneEmployee.employee + "')");
watchingRGs[oneEmployee.employee] = oneEmployee.resolverGroups;
watchResolverGroup("", oneEmployee.employee);
var accordionTextNode = document.createTextNode(oneEmployee.employee);
accordionButton.appendChild(accordionTextNode);
returnValues[0] = accordionButton;
var accordionDiv = document.createElement("div");
accordionDiv.className = "panel";
if (oneEmployee.reports.length > 0) {
for (var empInd = 0; empInd < oneEmployee.reports.length; empInd++) {
var thisEmpAcc = createAccordion(oneEmployee.reports[empInd]);
accordionDiv.appendChild(thisEmpAcc[0]);
accordionDiv.appendChild(thisEmpAcc[1]).click();
}
}
returnValues[1] = accordionDiv;
if(oneEmployee.resolverGroups.length > 0 ) {
accordionButton.click();
}
return returnValues;
}
function populateResolverGroups(resolverGroups, employeeName) {
document.getElementById('resolvergroups').innerHTML = "";
var rgList = resolverGroups.split(',');
for (var rgInd = 0; rgInd < rgList.length; rgInd++) {
var cbox = document.createElement('input');
cbox.setAttribute("onclick", "watchResolverGroup('"+rgList[rgInd]+"', '"+employeeName+"')");
cbox.type = "checkbox";
cbox.name = rgList[rgInd];
cbox.value = rgList[rgInd];
cbox.id = rgList[rgInd];
//cbox.checked = true;
//keeps track of the RGs that are checked
if (watchingRGs[employeeName] !== undefined) {
if (watchingRGs[employeeName].includes(rgList[rgInd])) {
cbox.checked = true;
}
}
var cboxTextNode = document.createTextNode(rgList[rgInd]);
var linebreak = document.createElement("br");
document.getElementById('resolvergroups').appendChild(cbox);
document.getElementById('resolvergroups').appendChild(cboxTextNode);
document.getElementById('resolvergroups').appendChild(linebreak);
}
}
function watchResolverGroup(resolverGroupName, employeeName) {
var selectedRGs = [];
if (watchingRGs[employeeName] !== undefined) {
selectedRGs = watchingRGs[employeeName];
}
if (resolverGroupName.length > 0) {
if (selectedRGs.includes(resolverGroupName)) {
selectedRGs.splice(selectedRGs.indexOf(resolverGroupName), 1);
} else {
selectedRGs.push(resolverGroupName);
}
}
watchingRGs[employeeName] = selectedRGs;
document.getElementById("selected_resolvergroups").innerHTML = "";
for (var key in watchingRGs) {
var val = watchingRGs[key];
for (var rgInd = 0; rgInd < val.length; rgInd++) {
var tempTextNode = document.createTextNode(val[rgInd] + " -> " + key);
var linebreak = document.createElement("br");
document.getElementById("selected_resolvergroups").appendChild(tempTextNode);
document.getElementById("selected_resolvergroups").appendChild(linebreak);
}
}
}
How to proceed with that?
For Open Close Hiracrhy this will help you
http://mleibman.github.io/SlickGrid/examples/example5-collapsing.html
Example
If you want to build your own take a look at this fiddle it will help
JS Fiddle
<table id="mytable">
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span>Item 1</td>
<td>123</td>
</tr>
<tr data-depth="1" class="collapse level1">
<td><span class="toggle"></span>Item 2</td>
<td>123</td>
</tr>
</table>

Multiple countdown timers comparing a given time and current time?

Really struggling with this part for some reason.
I'm creating a timer I can use to keep track of bids. I want to be able to compare two times and have the difference (in minutes and seconds) shown in the countdown column. It should be comparing the bid start time and the time right now.
Perhaps when it reaches bid start it could also change to show how long until bid ends. Eventually I want to add background changes once it's getting close to the time, and perhaps the ablility to set alarms with a prompt window.
Here's the code I have so far:
HTML
<table>
<tr>
<td>Item Name</td>
<td><input id="itemNameField" placeholder="" type="text"></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Time of Notice</td>
<td><input id="noticeField" type="time"></td>
</tr>
</table>
<input id="addButton" onclick="insRow()" type="button" value="Add Timer">
<div id="errorMessage"></div>
<hr>
<div id="marketTimerTableDiv">
<table border="1" id="marketTimerTable">
<tr>
<td></td>
<td>Item Name</td>
<td>Time of Notice</td>
<td>Bid Start</td>
<td>Bid End</td>
<td>Countdown</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div id="itembox"></div>Example Item
</td>
<td>
<div id="noticebox"></div>12:52
</td>
<td>
<div id="bidstartbox"></div>13:02
</td>
<td>
<div id="bidendbox"></div>13:07
</td>
<td>
<div id="countdownbox"></div>
</td>
<td><input id="delbutton" onclick="deleteRow(this)" type="button" value="X"></td>
</tr>
</table>
</div>
JAVASCRIPT
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
if (i == 1) {
console.log = "hi";
} else {
document.getElementById('marketTimerTable').deleteRow(i);
}
}
function insRow() {
if (itemNameField.value == "" || noticeField.value == "") {
var div = document.getElementById('errorMessage');
div.innerHTML = "*Please fill in the fields*";
div.style.color = 'red';
document.body.appendChild(div);
} else {
var div = document.getElementById('errorMessage');
div.innerHTML = "";
var x = document.getElementById('marketTimerTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var inp1 = new_row.cells[1].getElementsByTagName('div')[0];
inp1.id += len;
inp1.innerHTML = itemNameField.value;
itemNameField.value = "";
var inp2 = new_row.cells[2].getElementsByTagName('div')[0];
inp2.id += len;
inp2.innerHTML = noticeField.value;
noticeField.stepUp(10);
var inp3 = new_row.cells[3].getElementsByTagName('div')[0];
inp3.id += len;
inp3.innerHTML = noticeField.value;
noticeField.stepUp(5);
var inp4 = new_row.cells[4].getElementsByTagName('div')[0];
inp4.id += len;
inp4.innerHTML = noticeField.value;
var inp5 = new_row.cells[5].getElementsByTagName('div')[0];
inp5.id += len;
inp5.innerHTML = "";
noticeField.value = "";
x.appendChild(new_row);
}
}
I apologize in advance because my code is probably really messy and badly formatted. Here's a JSFIDDLE as well! Thanks :)
To calculate the difference between the current and given time, you can use setInterval
Example :
var noticeTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
var diffInHours = currentDate.getHours() - noticeTime[0];
var diffInMinutes = currentDate.getMinutes() - noticeTime[1];
inp5.innerHTML = diffInHours + ":" + diffInMinutes;
if(diffInHours === 0 && diffInMinutes === 0) {
clearInterval(interval);
}
},1000)
I managed to do it with the help of the code from ProgXx.
I added the following code:
var noticeTime = noticeField.value.split(":");
var originalTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
noticeTime[1] = originalTime[1] - currentDate.getMinutes() + 10;
noticeTime[1] = noticeTime[1] + (originalTime[0] * 60) - (currentDate.getHours() * 60);
Here's a JSFIDDLE of the finihsed code: http://jsfiddle.net/joefj8wb/

HTML Table cell - Recovering Values

I have a html table with a dynamic rows list, When I delete one of these rows I want to recover the value of the column 3 on the selected row to change an output text with the total value...
How do I do it with jquery or javascript ?
<div id="ven_mid">
<table id="tbprodutos" style="width:80%;margin:0 auto;float:left;text-align:center;">
<tr class="titulo">
<th>Referência</th>
<th>Numeração</th>
<th>Qtd</th>
<th>Valor - R$</th>
<th>Código</th>
<th>-</th>
</tr>
</table>
</div>
<script>
function deleteRow(i){
// here i need to remove the value "valor"
// of the selected row of the total.
document.getElementById('tbprodutos').deleteRow(i);
}
</script>
--- Add Row Script ---
<script>
$('#ven_prod').keypress(function (e)
{
if(e.keyCode==13)
{
var table = document.getElementById('tbprodutos');
var tblBody = table.tBodies[0];
var newRow = tblBody.insertRow(-1);
var prod = document.getElementById('ven_prod').value;
var qtd = document.getElementById('ven_qtd');
var barra = prod.substring(0, 12);
var num = prod.substring(14, 16);
var ref = "";
var valor = "";
var id = "";
var cor = "";
var mat = "";
var tot = document.getElementById('valortotal').value;
$.ajax({
type: "POST",
url: "System/ProcessaProdutos.jsp",
data: "pro_barras="+barra,
success: function(data){
var retorno = data.split(" ");
ref = (retorno[0]);
valor = (retorno[1]);
id = (retorno[2]);
mat = (retorno[3]);
cor = (retorno[4]);
if(prod.length==16) {
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<td>Ref: '+ref+' - '+mat+' '+cor+'</td>';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = '<td>'+num+'</td>';
var newCell2 = newRow.insertCell(2);
newCell2.innerHTML = '<td>'+qtd.value+'</td>';
var newCell3 = newRow.insertCell(3);
newCell3.innerHTML = '<td class="tbvalor">'+valor+'</td>';
var newCell4 = newRow.insertCell(4);
newCell4.innerHTML = '<td>'+barra+'</td>';
var newCell5 = newRow.insertCell(5);
newCell5.innerHTML = '<td><input type="button" value="Remover" onclick="deleteRow(this.parentNode.parentNode.rowIndex)"/></td>';
document.getElementById('ref').value = 'Referência: '+ref+' - '+mat+' '+cor;
document.getElementById('imgsrc').src = './?acao=Img&pro_id='+id;
updateTotal();
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
} else {
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
alert("Código de barras inválido!");
}
}
});
return false;
}
});
</script>
--- New "update total" function that solved the problem --
function updateTotal(){
var total = 0;
var rows = $("#tbprodutos tr:gt(0)");
rows.children("td:nth-child(4)").each(function() {
total += parseInt($(this).text());
});
document.getElementById('valortotal').value = total;
}
To expand on what Bartdude said, here is a more usable example. Lets say you have a table with the structure
<table id = 'tableData'>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
<tr>
<td class = 'col1'>1.1</td>
<td class = 'col2'>1.2</td>
<td class = 'col3'>1.3</td>
<td class = 'col4'>1.4</td>
<td class = 'col5'>1.5</td>
</tr>
</table>
Each time a delete operation occurs, you can just grab all the existing values and execute a sum or what mathematical operation you use and return the value
function updateTotal(){
var total = 0;
//loop over all table rows
$("#tableData").find("tr").each(function(){
//get all column 3 values and sum them for a total
total += $(this).find("td.col3").text();
}
return total;
}

Categories

Resources