Replace html element with data in javascript - javascript

I trying to auto increment the serial number when row increases and automatically readjust the numbering order when a row gets deleted in javascript. For that I am using the following clone method for doing my task. Rest of the thing is working correct except its not increasing the srno because its creating the clone of it. Following is my code for this:
function addCloneRow(obj) {
if(obj) {
var tBody = obj.parentNode.parentNode.parentNode;
var trTable = tBody.getElementsByTagName("tr")[1];
var trClone = trTable.cloneNode(true);
if(trClone) {
var txt = trClone.getElementsByTagName("input");
var srno = trClone.getElementsByTagName("span");
var dd = trClone.getElementsByTagName("select");
text = tBody.getElementsByTagName("tr").length;
alert(text) //here i am getting the srno in increasing order
//I tried something like following but not working
//var ele = srno.replace(document.createElement("h1"), srno);
//alert(ele);
for(var i=0; i<dd.length; i++) {
dd[i].options[0].selected=true;
var nm = dd[i].name;
var nNm = nm.substring((nm.indexOf("_")+1),nm.indexOf("["));
dd[i].name = nNm+"[]";
}
for(var j=0; j<txt.length; j++) {
var nm = txt[j].name;
var nNm = nm.substring((nm.indexOf("_")+1),nm.indexOf("["));
txt[j].name = nNm+"[]";
if(txt[j].type == "hidden"){
txt[j].value = "0";
}else if(txt[j].type == "text") {
txt[j].value = "";
}else if(txt[j].type == "checkbox") {
txt[j].checked = false;
}
}
for(var j=0; j<txt.length; j++) {
var nm = txt[j].name;
var nNm = nm.substring((nm.indexOf("_")+1),nm.indexOf("["));
txt[j].name = nNm+"[]";
if(txt[j].type == "hidden"){
txt[j].value = "0";
}else if(txt[j].type == "text") {
txt[j].value = "";
}else if(txt[j].type == "checkbox") {
txt[j].checked = false;
}
}
tBody.insertBefore(trClone,tBody.childNodes[1]);
}
}
}
Following is my html :
<table id="step_details" style="display:none;">
<tr>
<th width="5">#</th>
<th width="45%">Step details</th>
<th>Expected Results</th>
<th width="25">Execution</th>
<th><img src="gui/themes/default/images/ico_add.gif" onclick="addCloneRow(this);"/></th>
</tr>
<tr>
<td><span>1</span></td>
<td><textArea name="step_details[]"></textArea></td>
<td><textArea name="expected_results[]"></textArea></td>
<td><select onchange="content_modified = true" name="exec_type[]">
<option selected="selected" value="1" label="Manual">Manual</option>
<option value="2" label="Automated">Automated</option>
</select>
</td>
<td><img src="gui/themes/default/images/ico_del.gif" onclick="removeCloneRow(this);"/></td>
</tr>
</table>
I want to change the srno. of span element dynamically after increment and decrement on it.
Need help thanks

I think that what you want is something this:
var varcharCurrentNumber = trClone.getElementsByTagName("span")[0].innerHTML;
var nextNumber= eval(varcharCurrentNumber) +1;
trClone.getElementsByTagName("span")[0].innerHTML = nextNumber;

Related

How to add information to a table based on a button click in Javascript?

I have 2 functions, one dynamically creates a list, the other inserts a row after the row was added to the table.
What's happening now is when I click add to order, the product is added to the table, the new row is created, and when I click another product to add to the table, the old product disappears and the most recent product takes it's place and then creates a new row, so now I have 3 rows total, but only 1 product in the table, and 2 empty rows in the table. every time I add a product to the order, it just replaces the first row with the new product, and the old one is wiped away. I want every product I click to be added to the table and a new row created there after.
html:
<table id = "productsTable">
<tr>
<th>#</th>
<th>SKU</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Retail Price</th>
<th>List Price</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="productSKU" readonly ="true"/></td>
<td><input type="text" id="productName" readonly = "true"/></td>
<td><input type="text" id="quantity" /></td>
<td><input type="text" id="retailPrice" readonly = "true"/></td>
<td><input type="text" id="listPrice" readonly = "true"/></td>
<input type="button" id = "btnDeleteRow" value="-">
</tr>
</table>
JavaScript:
function populateProductList(jsonArr){
var html = "";
html += `<ul id="myULProducts">`;
for(var x = 0; x < jsonArr.length; x++){
html += `
<li SKU = "${jsonArr[x].SKU}">
<a href="#" class="products">
<strong>Product SKU:</strong> ${jsonArr[x].SKU}
<br><strong>Product Name:</strong> ${jsonArr[x].product_name}
<br><strong>Retail Price:</strong> ${jsonArr[x].retail_price}
<br><strong>List Price:</strong> ${jsonArr[x].list_price}
<br><br></a>
<button type="button" class="btnAddProductToOrder">Add to Order</button>
</li>
</div>`
}
html += `</ul>`;
var ol = document.createElement("ol");
ol.innerHTML = html;
var tableContainer = document.getElementById("product-list-container");
tableContainer.innerHTML = "";
tableContainer.appendChild(ol);
tableContainer.addEventListener("click", function(evt){
//populateCardGroupList();
var target = evt.target;
//if statement to see if the classList has a button edit
if(target.classList.contains("btnAddProductToOrder")){
//get the id of the card group clicked
var selectedId = target.closest("li").getAttribute("SKU");
//get the card group attached to that id and pass it the rest of the json Array of objects
var selectedProduct = getProductId(selectedId, jsonArr);
populateOrderFormProducts(selectedProduct);
}
});
}
document.getElementById("btnGetProductList").addEventListener("click", ()=>{
getAllProducts();
});
function populateOrderFormProducts(jsonArr){
document.querySelector("#productSKU").value = jsonArr.SKU;
document.querySelector("#productName").value = jsonArr.product_name;
document.querySelector("#quantity").value = 1;
document.querySelector("#retailPrice").value = jsonArr.retail_price;
document.querySelector("#listPrice").value = jsonArr.list_price;
insertRow();
}
function insertRow() {
var x = document.getElementById('productsTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = '';
var inp5 = new_row.cells[5].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = '';
x.appendChild(new_row);
}
This is what i'm trying to do but obviously this doesn't work:
function populateOrderFormProducts(jsonArr){
if(document.querySelector("#productSKU").value = null){
document.querySelector("#productSKU").value = jsonArr.SKU;
document.querySelector("#productName").value = jsonArr.product_name;
document.querySelector("#quantity").value = 1;
document.querySelector("#retailPrice").value = jsonArr.retail_price;
document.querySelector("#listPrice").value = jsonArr.list_price;
insertRow();
}
else if(document.querySelector("#productSKU").value != null){
document.querySelector("#productSKU2").value = jsonArr.SKU;
document.querySelector("#productName2").value = jsonArr.product_name;
document.querySelector("#quantity2").value = 1;
document.querySelector("#retailPrice2").value = jsonArr.retail_price;
document.querySelector("#listPrice2").value = jsonArr.list_price;
insertRow();
}
else if(document.querySelector("#productSKU2").value != null){
document.querySelector("#productSKU3").value = jsonArr.SKU;
document.querySelector("#productName3").value = jsonArr.product_name;
document.querySelector("#quantity3").value = 1;
document.querySelector("#retailPrice3").value = jsonArr.retail_price;
document.querySelector("#listPrice3").value = jsonArr.list_price;
insertRow();
}
}

Reorder CSV rows

I have this code which basically reads a CSV and should output a table where the CSV row content should be reordered!
Example :
fish;4;1;33
fish should be at 1 row column 4.
dog;5;2;66
dog should be at 2nd row column 5
The problem is that it doesn't print anything, neither at the console! Can you please show me where I am wrong? What modifications should I do?
My code:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var i = 0; i <lines.length; i++)
{
document.write("<th>");
document.write(" ");
document.write("</th>");
}
for (var i = 0; i <lines.length; i++)
{
document.write("<tr>");
for (var j = 0; j <lines.length; j++)
{
document.write("<td>");
document.write(" ");
document.write("</td>");
}
document.write("</tr>");
}
function insertData(id, content) {
var dataRows = content.split("\r");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
});
}
}
}
myReader.readAsText(theFile);
}
return false;
} //end
So, i did everything again for you with a big example.
I think you can handle it in your code, or take mine in the example.
Here are the main functions you can safely use in your case :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
And a working example you can use too, upload file is included (click on Run code snippet at the bottom of the post, and full page to test) :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
console.log('reorderLine',csvArray,a,b);
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
console.log('reorderColumn',csvLine,a,b);
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
// init element
var rawCsvFile = document.getElementById("csvInput");
var rawCsv = document.getElementById("rawCsv");
var reorderedRawCsv = document.getElementById("reorderedRawCsv");
var lines = document.getElementById("lines");
var lineA = document.getElementById("lineA");
var lineB = document.getElementById("lineB");
var colA = document.getElementById("colA");
var colB = document.getElementById("colB");
var apply = document.getElementById("apply");
var reset = document.getElementById("reset");
var rawCsvData, reorderCsvData;
// file uploaded
rawCsvFile.addEventListener("change", function() {
// reader
var reader = new FileReader();
// the file is loaded
reader.onload = function(e) {
// cancel if undefined
if(!reader.result || typeof reader.result != "string") return;
// Get result from new FileReader()
rawCsvData = reader.result.split(/[\r\n]+/g); // split lines
rawCsv.innerHTML = reader.result; // show in textarea
reorderedRawCsvData = rawCsvData; // clone data at start
function showCsvValueInForm(){
// empty fields
lines.innerHTML = "";
lineA.innerHTML = "";
lineB.innerHTML = "";
colA.innerHTML = "";
colB.innerHTML = "";
// Show in Raw CSV textarea
reorderedRawCsv.innerHTML = reorderedRawCsvData.join("\r\n");
// Add All option in On
var toAll = document.createElement('option');
toAll.value = "all";
toAll.innerHTML = "All";
lines.appendChild(toAll);
// handle line change
reorderedRawCsvData.map(function(val,i){
var lineOpt = document.createElement('option');
lineOpt.value = i;
lineOpt.innerHTML = i + " - " +(val.split(';'))[0];
// add options in line selects
lines.appendChild(lineOpt.cloneNode(!!1));
lineA.appendChild(lineOpt.cloneNode(!!1));
lineB.appendChild(lineOpt);
});
// handle col change
var nCol = rawCsvData[0].split(';');
nCol.map(function(val,i){
var colOpt = document.createElement('option');
colOpt.value = i;
colOpt.innerHTML = i;
// add options in col selects
colA.appendChild(colOpt.cloneNode(!!1));
colB.appendChild(colOpt);
});
// create table
csvArrayToTable(reorderedRawCsvData,"reorderedCsvTable");
}
// fill select, option and table with the reordered csv data
showCsvValueInForm();
// apply event, change the order
apply.addEventListener("click", function() {
// reordering line
var lineAOpt = lineA.options[lineA.selectedIndex].value;
var lineBOpt = lineB.options[lineB.selectedIndex].value;
if(lineAOpt !== lineBOpt) reorderedRawCsvData = reorderLine(reorderedRawCsvData,lineAOpt,lineBOpt);
// reordering col (all or only one)
var colAOpt = colA.options[colA.selectedIndex].value;
var colBOpt = colB.options[colB.selectedIndex].value;
if(colAOpt !== colBOpt)
if(lines.value == "all"){
reorderedRawCsvData = reorderedRawCsvData.map(function(val,i){
return reorderColumn(val,colAOpt,colBOpt);
});
}else{
reorderedRawCsvData[lines.value] = reorderColumn(reorderedRawCsvData[lines.value],colAOpt,colBOpt);
}
// fill again
showCsvValueInForm();
});
// reset the form with raw values
reset.addEventListener("click", function() {
if (confirm("Are you sure ?")) {
// reset
reorderedRawCsvData = rawCsvData;
// fill again
showCsvValueInForm();
}
});
}
// read the uploaded csv file as text
reader.readAsText(event.target.files[0], 'utf-8');
});
body { padding:10px; background:#eee; text-align: left; font-family: sans-serif; }
fieldset { width:80%; background:#fff; }
<html>
<head>
<title>CSV Reorder</title>
</head>
<body>
<h1>Reorder CSV</h1>
<fieldset>
<h3>Step 1 - Raw CSV</h3>
<small>Load a CSV file (not nested)</small>
<br />
<input type="file" id="csvInput">
<br />
<br />
<div>
<textarea id="rawCsv" placeholder="Waiting for a file..."></textarea>
</div>
</fieldset>
<br />
<fieldset>
<h3>Step 2 - Reordering Option</h3>
<small>Choose how to order the CSV data</small>
<br />
<table>
<tr>
<td>Line</td>
<td><select id="lineA"></select></td>
<td><=></td>
<td><select id="lineB"></select></td>
</tr>
<tr>
<td>Column</td>
<td><select id="colA"></select></td>
<td><=></td>
<td><select id="colB"></select></td>
<td>on</td>
<td><select id="lines"></select></td>
</tr>
<tr>
<td colspan="4"><button id="apply">Apply</button> <button id="reset">Reset</button></td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<h3>Step 3 - Reordered CSV</h3>
<small>Get the reordered values</small>
<br />
<div>
<textarea id="reorderedRawCsv" placeholder="Waiting for options..."></textarea>
</div>
<div>
<h3>Reordered CSV in a table</h3>
<div id="reorderedCsvTable">
<small>Waiting for a file..</small>
<br />
</div>
</div>
</fieldset>
</body>
</html>
Enjoy !

Search for a tag's name inside of a cell inside of each row

So pretty much I have it to were it's searching for the innerHTML of the td in question in each row....however I'm trying to grab the input name attribute from below
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>
Here's what i have so far
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for (var i = 0; i < rows.length; i++) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if (fullname) {
if (v.length == 0 ||
(v.length < 3 && fullname.indexOf(v) == 0) ||
(v.length >= 3 && fullname.indexOf(v) > -1)) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
var n = document.getElementById("noresults");
if (on == 0 && n) {
n.style.display = "";
document.getElementById("qt").innerHTML = q.value;
} else {
n.style.display = "none";
}
However right now it's only indicating within the td.... How do I get the above to look for the name of the input inside of the td?
Much appreciated.
You don't need a lot of code for that. On most modern browser this works.
//For 1 value
myInput = document.querySelector('#tablename td [name="Client"]');
console.log(myInput);
//For more values
myInput2 = document.querySelectorAll('#tablename td [name="Client"]');
console.log(myInput2); //it's an array now
//Like this?
myInput3 = document.querySelector('#tablename td [name]');
if(myInput3.getAttribute('name') == 'Client'){
myInput3.setAttribute('name', 'something');
}
console.log(myInput3.parentElement);
<table id="tablename">
<tr>
<td><input name="Client"></td>
</tr>
</table>
If you have a reference to the <td> element, you can use querySelector to get a reference to the <input> (assuming it's the only or first <input> descendant) and then getAttribute to get the value of the name attribute:
// You already have a reference to the <td>
const td = document.querySelector('td');
// Get the <input>
const input = td.querySelector('input');
// Get its `name` attribute
const name = input.getAttribute('name');
console.log('name is "%s"', name);
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>

how to add checkboxes in cells of first column of HTML table?

I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});

Find if a cell contents appears more than once

I have a table body that looks like the following:
<tbody>
<tr class="basket_main">
<td class="basket_item">
<input type="text" class="basket_qty_txt" id="ctl00_ctl00_main_body_content_main_content_area_shopping_basket_ctl01_txt_qty_162" value="3" name="ctl00$ctl00$main_body_content$main_content_area$shopping_basket$ctl01$txt_qty_162">
</td>
<td class="basket_item prod_code" id="ctl00_ctl00_main_body_content_main_content_area_shopping_basket_ctl01_prod_code_col">
CSM160
</td>
<td class="basket_item">
SIL.MTG:RENAULT R19 1988 ON
</td>
<td class="basket_item max_qty">
5
</td>
<td class="basket_item">
<input type="button" class="basket_item_button">
<input type="button" class="basket_item_button">
</td>
</tr>
</tbody>
There could be many rows in this table, what I'm trying to find out is if the prod_code appears in more than one row in the table using javascript or jquery.
Iterate through the table cells and collect the data.
Live demo http://jsfiddle.net/kEAzB/6/
var items = {};
$('tr td.basket_item.prod_code').each(function(){
var value = $(this).text();
if (items[value] == undefined) {
items[value] = 0;
}
items[value] += 1;
});
for (key in items) {
alert(key + ":" +items[key]);
}
You could scan all the table rows, store the product codes in an Associative Array (ie productCodes and check if the same product code is already defined.
var productCodesTds = document.getElementsByClassName("prod_code"),
productCodes = Object.create(null),
max,
i;
for (i = 0, max = productCodesTds; i < max; i += 1) {
productCode = productCodesTds[i].innerText;
if (productCode in productCodes) {
// the productCode is already defined in an other td
}
else {
productCodes['productCode'] = null;
}
}
push all the codes to array
var arr = new Array();
$('.prod_code').each(function(){
var prod_code = $(this).val();
arr.push(prod_code);
});
sort the array and check if there are duplicate values
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i += 1) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
alert("duplicate value"+sorted_arr[i + 1]);
}
}

Categories