Javascript Dynamic Accordion Help needed - javascript

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>

Related

Generated row of table event listener not working instantly

I have a table like this :
I have added an event listener assetTableEvent() to each text box in the table. My issue is when I add new row to the table, i also add the corresponding event listener to it assetTableEvent(), but the total value does not pop while entering value, it shows only when next row has values entered.
function assetTableEvent() {
let total = 0;
for (var k = 0; k < document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
I even tried calling assetTableEvent() every time there is a change, but it just does not work. Can somebody help me in Javascript how to make dynamically added rows correspond to event listener like above rows.
HTML for Asset table:
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>
And add row event listener :
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
Trying to use incremental IDs is more work than it is worth, especially when you start removing rows.
I suggest you use classes instead and delegate the event listener to the table itself. When an input event occurs you get the closest row and query for the elements within that row for the row total, then query all of the rows totals for the master total
Basic example with functional add row
const table = document.querySelector('#myTable'),
cloneRow = table.rows[0].cloneNode(true);
table.addEventListener('input',(e) => {
if (e.target.matches('.qty, .price')) {
const row = e.target.closest('tr'),
price = row.querySelector('.price').valueAsNumber || 0,
qty = row.querySelector('.qty').valueAsNumber || 0;
row.querySelector('.amt').value = qty * price;
setTotalAmt()
}
});
document.querySelector('#add-row').addEventListener('click', (e) => {
table.appendChild(cloneRow.cloneNode(true))
});
function setTotalAmt() {
const sum = [...table.querySelectorAll('.amt')].reduce((a, el) => a + (+el.value || 0), 0)
document.querySelector('#total').value = sum;
}
<button id="add-row">
Add Row
</button>
Total:<input id="total" />
<table id="myTable">
<tr>
<td>Qty:
<input type="number" class="qty" value="0" />
</td>
<td>Price:
<input type="number" class="price" value="0" />
</td>
<td>Amt:
<input class="amt" readonly value="0" />
</td>
</tr>
</table>
#charlietfl 's solition is more elegant but if you wonder what is the problem in your code, you should change the < to <= in k < document.getElementById("assetTable").rows.length; part
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
Here is the working example:
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>

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>

Velocity/Java script form not retaining the input

I am having trouble with velocity scripts which is not returning the childDoc(s) values after clicking the Apply button (child doc value disappears). I am new to Velocity and the Javascript.
Below is the part of the code that uses a form.
#set($levelRow = "levelRow")
#set($newLevelRow = "newLevelRow")
{pre}
<script>
function removeLevel(prefix) {
var levels = updateCommon(false, prefix);
var removeRow = document.getElementById(prefix + "levelRow" + levels);
removeRow.parentNode.removeChild(removeRow);
if(levels > 2)
setActionImageVisibility(levels - 1, "visible", prefix);
}
function addLevel(prefix) {
var levels = updateCommon(true, prefix);
var lastLevelRow = document.getElementById(prefix + "levelRow" + levels);
var newLevelRow = document.getElementById(prefix + "newLevelRow");
var newLevelInput = newLevelRow.getElementsByTagName("input")[0];
var toInsertRow = lastLevelRow.cloneNode(true);
toInsertRow.setAttribute("id", prefix + "levelRow" + (levels + 1));
var toInsertInputs = toInsertRow.getElementsByTagName("input");
var toInsertInput = null;
var toInsertOutput = null;
for (var i = 0; i < toInsertInputs.length; i++) {
var input_id = toInsertInputs[i].getAttribute("id");
if (input_id == (prefix + "query" + (levels))) {
toInsertInput = toInsertInputs[i];
} else if (input_id == (prefix + (levels))) {
toInsertOutput = toInsertInputs[i];
}
}
toInsertInput.setAttribute("id", prefix + "query" + (levels + 1));
toInsertInput.value = newLevelInput.value;
toInsertOutput.setAttribute("id", prefix + (levels + 1));
toInsertOutput.name = prefix + (levels + 1);
toInsertOutput.value = toInsertInput.value.replace("/#/", "/redirect/");
newLevelInput.value = "";
newLevelRow.parentNode.insertBefore(toInsertRow,newLevelRow);
setActionImageVisibility(levels, "hidden", prefix)
setActionImageVisibility(levels + 1, "visible", prefix)
}
function updateCommon(add,prefix) {
var levelsInput = document.getElementById(prefix + "levelsInput");
var levels = levelsInput.getAttribute("value") - 1 + 1;
if(add) {
levelsInput.setAttribute("value", levels + 1);
} else {
levelsInput.setAttribute("value", levels - 1);
}
return levels;
}
function setActionImageVisibility(level,visibility,prefix) {
var img = document.getElementById(prefix + "levelRow" + level).getElementsByTagName("img")[0];
img.style.visibility = visibility;
}
function submitFunction() {
var input_prefixes = new Array();
var docElements = document.getElementsByTagName("input");
for (docElement in docElements) {
var indexLevels = docElement.indexOf("levels");
var levelsAtEnd = (indexLevels + "levels".length) == docElement.length;
var hasPrefix = docElement.length > "levels".length;
if ((-1 < indexLevels) && levelsAtEnd && hasPrefix) {
input_prefixes.push(docElement.substring(0,indexLevels));
var input_prefix = docElement.substring(0,indexLevels);
var levelsInput = document.getElementsByName(docElement).item(0);
for (var i=1; i < parseInt(levelsInput.value) + 1; i++) {
var input = document.getElementById(input_prefix + "query" + String(i));
var output = document.getElementsByName(input_prefix + String(i)).item(0);
output.value = input.value.replace("/#/", "/redirect/");
}
}
}
}
</script>
{/pre}
#macro(loadParameter $id)
#set($_id = "$id")
#set($parameter = false)
#set($parameter = $request.getParameter($_id))
#end
#macro(VariableInputTable $paramBaseName $parametersRedirect)
#set($parameterPrefix = "${paramBaseName}")
#loadParameter("${parameterPrefix}levels")
#set($levels = $parameter)
#set($requiresParamInit = !$levels)
#if($requiresParamInit)
#set($defaultQueries = [""])
#set($levels = ${defaultQueries.size()})
#set($initParameters = "${parameterPrefix}levels=${levels}") ## this assumes that it is setting the only parameters on the page
#foreach($query in $defaultQueries)
#set($initParameters = "$initParameters&${parameterPrefix}${velocityCount}=$query")
#end
#set($parametersRedirect = "${parametersRedirect}${initParameters}")
#else
#set($int = 0)
#set($levels = $int.valueOf($levels))
#showTable()
#end
#end
#macro(showTable)
#set($queries = [])
#set($linkRoles = [])
#set($sorts = [])
<input id="${parameterPrefix}levelsInput" type="hidden" name="${parameterPrefix}levels" value="$levels"></input>
<table cellpadding="0" border=0>
#foreach($level in [1..$levels])
#loadParameter("${parameterPrefix}${level}")
<tr id="${parameterPrefix}${levelRow}$level">
<td style="border-width:1px;border-style:solid;padding:1px">
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" oninput="submitFunction()" #if($parameter)value="$parameter.replaceAll('"','\\"')#end">
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" style="width: 100%;">
</td>
<td style="vertical-align:middle;text-align:center;">
<img src="/polarion/ria/images/control/minus.gif" alt="Remove" title="Remove" style="cursor:pointer#if(($velocityCount != $levels) || (2 > $levels));visibility:hidden#end" onclick="removeLevel('${parameterPrefix}')" id="${parameterPrefix}removeImg$level"></img>
</td>
</tr>
#if($parameter)#set($void = $queries.add($parameter))#end
#set($void = $linkRoles.add([]))
#set($void = $sorts.add("id"))
#end
<tr id="${parameterPrefix}${newLevelRow}">
<td style="border-width:1px;border-style:solid;padding:1px">
<input style="border-style:none" id="${parameterPrefix}newQuery" type="text" size="50">
</td>
<td style="vertical-align:middle;text-align:center;">
<img src="/polarion/ria/images/control/plus.gif" alt="Add" title="Add" style="cursor:pointer" onclick="addLevel('${parameterPrefix}')"></img>
</td>
</tr>
</table>
#end
I think something wrong with below part.
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" oninput="submitFunction()" #if($parameter)value="$parameter.replaceAll('"','\\"')#end">
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" style="width: 100%;">
Form looks like:
I have managed to fix this by changing the code.
#if($parameter) #set( $childDocurl = $parameter.replaceAll('"','\\"'))#end
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" value="${childDocurl}" oninput="submitFunction()" >
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" value="${childDocurl}" style="width: 100%;">

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>

Replacing HTML content with dojo and javascript

Have made a table and stored it in a variale getcontent by using basic HTML.
getcontent="<table style="height: 1000px; ; width: 500px;" border="1">
<tbody>
<tr>
<td>[Assignment name]</td>
<td>[<span>Approximate Value of Contract</span>]</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>"
Contentinsquare is an array containg string which can be filled in th table. (SQUARE BRACKETS] in getcontent
contentinsquare=["name","100$"]
i want the value of contentinsqaure to be placed in between the sqaure brackets.For that i have used the code :-
var contentinsquare=["name","100$"]
var strInputCode = contentinsquare[1].replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";
});
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
contentinsquare[1]=strTagStrippedText
var strforlabelname = []
var strfortextarea = []
var strfortext = []
var str = []
label = dojo.query('label');
console.log(label, "all label names")
for( i = 0; i < label.length; i++)
{
if(label[i].id != "")
{
inner = dojo.byId(label[i].id).innerHTML
var name = inner.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
strforlabelname.push(name)
}
}
console.log(strforlabelname, "string")
text = dojo.query('input')
for( i = 0; i < text.length; i++)
{
if(text[i].id == "")
{
}
else
{
innertext = dijit.byId(text[i].id).getValue();
str.push(innertext)
//console.log(str,"strng1")
}
}
textarea = dojo.query('textarea')
for( i = 0; i < textarea.length; i++)
{
if(textarea[i].id == ""||textarea[i].id =="textareaidfirst")
{
}
else
{
innertextarea = dojo.byId(textarea[i].id).value
str.push(innertextarea)
}
}
for( i = 0; i < strforlabelname.length; i++)
{
for( j = 0; j < contentinsquare.length; j++)
{
if(contentinsquare[j] == strforlabelname[i])
{
var patt = new RegExp("\\[" + strforlabelname[i] + "\\]", "g")
getcontent = getcontent.replace(patt, str[i]);
}
}
}
This results to :-
Result :-
"<table style="height: 1000px; ; width: 500px;" border="1">
<tbody>
<tr>
<td>name</td>
<td>[<span>Approximate Value of Contract</span>]</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>"
that is the sqaure brackets contaning <span> tag is not working. i want the 100 $ to be replaced over thr.

Categories

Resources