HTML Table cell - Recovering Values - javascript

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;
}

Related

JQuery Highlight Row and Column in table

I want to add to my site table with highlighting row and column, but I have troubles with
column highlighting. This is my table. This is online courses and a full the table with
names such as Homework1, HW2 and etc.
%if len(students) > 0:
<div class="grades">
<table class="grade-table">
<%
templateSummary = students[0]['grade_summary']
%>
<thead>
<tr class = "table-header"> <!— Header Row —>
%for section in templateSummary['section_breakdown']:
//......
<th title="${tooltip_str}"><div class="assignment-label">${section['label']}</div></th>
%endfor
<th title="${_('Total')}"><div class="assignment-label">${_('Total')}</div></th>
</tr>
</thead>
<%def name="percent_data(fraction, label)">
//....
<td class="${data_class}" data-percent="${fraction}" title="${label}">${ "{0:.0f}".format( 100 * fraction ) }</td>
</%def>
<tbody>
%for student in students:
<tr class="table-row">
%for section in student['grade_summary']['section_breakdown']:
${percent_data( section['percent'], section['detail'] )}
%endfor
${percent_data( student['grade_summary']['percent'], _('Total'))}
</tr>
%endfor
</tbody>
</table>
This is JQuery. So in highlightRow() is making the magic with row, but I don't understand,
to add highlightColumn() and "$element.find('tr').bind('mouseover', highlightColumn);" or
to add in the function highlightRow() code for column.
var Gradebook = function($element) {
"use strict";
var $body = $('body');
var $grades = $element.find('.grades');
var $studentTable = $element.find('.student-table');
var $gradeTable = $element.find('.grade-table');
var $search = $element.find('.student-search-field');
var $leftShadow = $('<div class="left-shadow"></div>');
var $rightShadow = $('<div class="right-shadow"></div>');
var tableHeight = $gradeTable.height();
var maxScroll = $gradeTable.width() - $grades.width();
var mouseOrigin;
var tableOrigin;
var startDrag = function(e) {
mouseOrigin = e.pageX;
tableOrigin = $gradeTable.position().left;
$body.addClass('no-select');
$body.bind('mousemove', onDragTable);
$body.bind('mouseup', stopDrag);
};
var highlightRow = function() {
$element.find('.highlight').removeClass('highlight');
var index = $(this).index();
$studentTable.find('tr').eq(index + 1).addClass('highlight');
$gradeTable.find('tr').eq(index + 1).addClass('highlight');
};
$leftShadow.css('height', tableHeight + 'px');
$grades.append($leftShadow).append($rightShadow);
setShadows(0);
$grades.css('height', tableHeight);
$gradeTable.bind('mousedown', startDrag);
$element.find('tr').bind('mouseover', highlightRow);
$search.bind('keyup', filter);
$(window).bind('resize', onResizeTable);
};
It should be something like this:
$element.find('td').bind('mouseover', highlightColumn);
var highlightColumn = function() {
//remove all highlights
//not sure if it should be here may be it should happen before both highlightRow and highlightColumn function calls
$element.find('.highlight').removeClass('highlight');
var columnIndex = $(this).index(); //this should be td in this case
$studentTable.find('tr td:eq(' + columnIndex + ')').addClass('highlight');
$gradeTable.find('tr td:eq(' + columnIndex + ')').addClass('highlight');
};

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>

Insert table header dynamically using javascript

I am trying to add a table header only once on to the top of a table. I have a code where I am able to generate header after inserting a row. I am missing the indexing here. where I am able to add header only after inserting the second row. Could you please help me fix a minor error here. I would not want to pass any object from html page.
var table = document.getElementById("Table");
// Empty tables
while(table.rows.length > 0) {table.deleteRow(0);}
// Add rows
for (var i = 1; i<data.Contents.length; i++) {
var row = table.insertRow(i-1);
var cell1 = row.insertCell(0), cell2 = row.insertCell(1),cell3 = row.insertCell(2),cell4 = row.insertCell(3),cell5 = row.insertCell(4),cell6 = row.insertCell(5),cell7 = row.insertCell(6);
var cell8 = row.insertCell(7), cell9 = row.insertCell(8),cell10 = row.insertCell(9),cell11 = row.insertCell(10),cell12 = row.insertCell(11),cell13 = row.insertCell(12),cell14 = row.insertCell(13);
//Code for header
var header = document.getElementById("Table").rows[0].cells;
header[0].innerHTML = " ";
header[1].innerHTML = " ";
header[2].innerHTML = "<b>NAME</b>";
header[4].innerHTML = "<b>MODIFIED</b>";
header[6].innerHTML = "<b>TIME</b>";
header[8].innerHTML = " ";
header[10].innerHTML = "<b>MORE</b>";
header[12].innerHTML = " ";
//column1: file icon
var btn_fileIcon = document.createElement("input");
btn_fileIcon.setAttribute("type","image");
btn_fileIcon.setAttribute("src","images/file.png");
btn_fileIcon.setAttribute("style","height:20px;width:20px");
cell2.appendChild(btn_fileIcon);
// column2: file name
cell3.innerHTML = data.Contents[i].Key.replace(folderName+'/', '');//data.Contents[i].Key;
// Time
var str = dateModified( data.Contents[i].LastModified);
cell5.innerHTML = " " + str;
cell5.setAttribute("style","padding-left: 4cm");
cell5.setAttribute("position","fixed");
cell5.style.textAlign = "center";
// size
var s = Math.round( data.Contents[i].Size/1024);
var fileSize = s.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
cell7.innerHTML = fileSize + " KB";
cell7.setAttribute("style","padding-left: 4cm");
cell7.setAttribute("position","fixed");
cell7.style.textAlign = "center";
// column3: download (csv)
var btn_download = document.createElement("input");
btn_download.setAttribute("type","image");
btn_download.setAttribute("src","images/download-button.png");
btn_download.setAttribute("style","height:20px;width:20px;margin-left: 100px;margin-right: 10px;");
btn_download.setAttribute("onclick","load2local(this);");
btn_download.fileName = data.Contents[i].Key;
cell9.appendChild(btn_download);
// column4: delete
var btn_delete = document.createElement("input");
btn_delete.setAttribute("type","image");
btn_delete.setAttribute("src","images/close-browser.png");
btn_delete.setAttribute("style","height:20px;width:20px;margin-left: 10px;margin-right: 10px;");
btn_delete.setAttribute("onclick","deleteObj(this);");
btn_delete.fileName = data.Contents[i].Key;
cell11.appendChild(btn_delete);
// load to NB
var btn_load2NB = document.createElement("input");
btn_load2NB.setAttribute("type","image");
btn_load2NB.setAttribute("src","images/eye.png");
btn_load2NB.setAttribute("style","height:25px;width:25px;margin-left: 10px;margin-right: 10px;");
btn_load2NB.fileName = data.Contents[i].Key;
btn_load2NB.setAttribute("onclick","load2NB(this);");
btn_load2NB.fileSize = data.Contents[i].Size;
cell13.appendChild(btn_load2NB);
// checkbox
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("name", "all");
checkbox.setAttribute("value", "ff");
checkbox.fileName = data.Contents[i].Key;
cell1.appendChild(checkbox);
checkbox.checked = false;
var element = document.createElement('hr');
// element.setAttribute("style","border: 1px solid black;text-align: left; margin-left: 2%; margin-right:2%;");
element.filename = data.Contents[i].Key;
cell14.appendChild(element);
}
Could you please help me to add a header once dynamically to a table?
This is one way to dynamically add table headers.
<html>
<script>
const tableHeaders = ['My Header1','My Header2','My Header3','My Header4'] // your header titles go here
function createNewTableHeader(headerTitle){
const temp = document.createElement('th');
temp.appendChild(document.createTextNode(headerTitle));
return temp
}
function addHeader() {
var tableHeaderPlaceHolder = document.getElementById('table-header-place-holder');
tableHeaders.forEach(header=>{
tableHeaderPlaceHolder.appendChild(createNewTableHeader(header));
})
}
document.addEventListener("DOMContentLoaded", function(event) {
addHeader();
});
</script>
<body>
<table id='table' cellspacing="20">
<tbody>
<tr id='table-header-place-holder'>
</tr>
</tbody>
<tbody>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
<td>data4</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
<td>data4</td>
</tr>
</tbody>
</table>
</body>
</html>

Sum values in column

I can't sum the subtotals of an HTML column table using javascript. I need to sum the 5th column and put the result in a textbox so the costumer can see the totals of his bill. The thing is, I can't use database because it is a table that doesn't INSERT the value in the database until I hit the final button. Any help would be appreciated. Thanks a lot
var arr2 = "";
$('#añadir').click(function() {
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
var subtotal = (cantidad * punitario)
if (id_pla != "" && cantidad != "") {
var row = table.insertRow(cant);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
cell0.innerHTML = cant;
cell1.innerHTML = id_pla;
cell2.innerHTML = pla;
cell3.innerHTML = cantidad;
cell4.innerHTML = punitario;
cell5.innerHTML = subtotal;
cant++;
arr2 += id_pla + "," + cantidad + ","
$('#arr').val(arr2);
}
validar();
});
This is the HTML code
<table id="tablaC" class="table table-hover">
<thead>
<tr>
<th>ID Pedido</th>
<th>ID Plato</th>
<th>Plato</th>
<th>Cantidad</th>
<th>Precio Unitario</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<input id="arr" name="arr" value="" />
<br>
<br/>
<input class="btn btn-info" type="submit" value="Crear Registro" id="registro">
</form>
<p></p>
I notice several issues in your files codes, you should fix them in order to make this work:
1)
To compare with "" You should use strict equality "!==" instead of "!="
if (id_pla !== "" && cantidad !== "") {
instead of:
if (id_pla != "" && cantidad != "") {
2) "$" is not defined as a variable, unless you refer to jQuery.
/*here*/ $('#añadir').click(function() {
3) Ids missing in your HTML code:
Here you are saying:
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
But you are not giving any id to this elements on your html. It should be like this:
<th>ID Pedido</th>
<th id="plato_id">ID Plato</th>
<th id="plato_nombre">Plato</th>
<th id="cantidad">Cantidad</th>
<th id="plato_precio">Precio Unitario</th>
<th>Subtotal</th>

Updating row ID when swapping HTML table rows

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>

Categories

Resources