Iterate through a table using JavaScript to get values of specific cells - javascript

How can I iterate through a table using JavaScript to get the values of cells 4 and 5?
This is what I have:
function constructString() {
var table=document.getElementById('wcList');
for(var i=0; i<table.rows.length;i++){
var row = getElem(RowId + i);
var str_wc = table.rows[i].cells[1].firstChild.value;
var str_act = table.rows[i].cells[5].firstChild.value;
var str_coh = table.rows[i].cells[6].firstChild.value;
var str_mconf = table.rows[i].cells[7].firstChild.value;
var string1 = str_wc + row + str_act + row + str_coh + row + str_mconf + row;
}
}

Use innerHTML.
Try this:
function constructString() {
var table=document.getElementById('wcList');
for(var i=0; i<table.rows.length;i++){
// FIX THIS
var row = 0;
var str_wc=(table.rows[i].cells[1].innerHTML);
var str_act=(table.rows[i].cells[5].innerHTML);
var str_coh=(table.rows[i].cells[6].innerHTML);
var str_mconf=(table.rows[i].cells[7].innerHTML);
var string1=str_wc +row+str_act+row+str_coh+row+str_mconf+row;
alert(string1);
}
}

Related

concatenate dynamic columns using google appscript

I want to concatenate columns that are dynamic, using appscript programmatically.
See the screenshot what my data looks like and what output i am trying to achieve:
I was able to achieve concatenation of static/fixed no. of columns using the below code.
function concatenate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ss.getSheetByName("Sheet1");
var lr = sheetName.getLastRow();
var lc = sheetName.getLastColumn();
var rangeValue = sheetName.getRange(2, 1, lr-1, lc).getValues();
for(var i=0;i<rangeValue.length; i++) {
var setRange = sheetName.getRange(i+2, lc);
setRange.setValue(rangeValue[i][0] + " " + rangeValue[i][1] + " " + rangeValue[i][2])
};
};
All i want to achieve now is, the same above for DYNAMIC columns. I tried my best to figure it out, but in vain. Any help would be much greatly appreciated.
Splicing in another column
This assumes that you start with only your data columns and that you have not added the header for the new column. It can be made to work both ways but you just need to know what your starting with.
function myFunction() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet 1');
var rg=sh.getDataRange();
var vA=rg.getValues();
for(var i=0;i<vA.length;i++){
if(i==0){
vA[i].splice(vA[i].length,0,'Concatenate');
}else{
vA[i].splice(vA[i].length,0,vA[i].join(' '));
}
}
sh.getRange(1,1,vA.length,vA[0].length).setValues(vA);
}
I believe you can solve this by just looping through the columns using the last column index lc variable you already have. Should look something like this:
function concatenate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ss.getSheetByName("Sheet1");
var lr = sheetName.getLastRow();
var lc = sheetName.getLastColumn();
var rangeValue = sheetName.getRange(2, 1, lr-1, lc).getValues();
for(var i = 0; i < rangeValue.length; i++) {
var catValues = "";
for (var j = 0; j < lc; j++) {
catValues += rangeValue[i][j] + " ";
}
var setRange = sheetName.getRange(i+2, lc);
setRange.setValue(catValues);
};
};
Or if you wanted to get fancy with .join():
function concatenate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ss.getSheetByName("Sheet1");
var lr = sheetName.getLastRow();
var lc = sheetName.getLastColumn();
var rangeValue = sheetName.getRange(2, 1, lr-1, lc).getValues();
for(var i = 0; i < rangeValue.length; i++) {
var catValues = sheetName.getRange(i, lc).getValues().join(" ");
var setRange = sheetName.getRange(i+2, lc);
setRange.setValue(catValues);
};
};

How to get the key names from the JavaScript array?

I am creating a page where I want to print the values like below the code snippet using the map function in JavaScript.
var kvArray = [{a:1, b:2},{a:3, b:4},{a:5, b:6}];
function getValue(item,index) {
var vm="<table/>"
var fullValue =[item.a +" "+ item.b];
var v=vm+fullValue
return v;
}
function myFunction() {
document.getElementById("demo").innerHTML =kvArray.map(getValue).join(" ")
}
I am getting the output like this:
1 2
3 4
5 6
But I want the actual output like this:
a b
1 2
3 4
5 6
Please see the following snippet for a working example:
var kvArray = [{a:1, b:2},{a:3, b:4},{a:5, b:6}]
var asCell = v => `<td>${v}</td>`
var asRow = v => `<tr>${v}</tr>`
$('#demo > thead > tr').html(
Object.keys(kvArray[0]).map(key => asCell(key))
)
$('#demo > tbody').html(
kvArray.map(entry => {
return asRow(Object.keys(entry).map(k => {
return asCell(entry[k])
}).join())
})
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="demo">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
I used Object.keys(kvArray[0]) to get the "column names".
var kvArray = [{a:1, b:2},{a:3, b:4},{a:5, b:6}];
function getValue(item,index)
{
var vm="<table/>"
var fullValue =[item.a +" "+ item.b];
var v=vm+fullValue
return v;
}
function createTable(kvArray)
{
var tableOpening="<table>";
var tableClosing="</table>";
var headerOpening= "<th>";
var headerClosing= "</th>";
var rowOpening= "<tr>";
var rowClosing= "</tr>";
var cellOpening= "<td>";
var cellClosing= "</td>";
// get the keys from the first element
var keys = Object.keys(kvArray && kvArray[0]) ;
// create a header
var header = rowOpening;
for (var keyIndex in keys) {
header += headerOpening + keys[keyIndex] + headerClosing + "\n";
}
header += rowClosing;
var table = tableOpening + header;
// create a row for each element
for (var itemIndex in kvArray) {
// open the row element
var rowLine = rowOpening;
for (var keyIndex in keys) {
// fill the cells
rowLine += cellOpening + kvArray[itemIndex][keys[keyIndex]] + cellClosing + "\n";
}
// close the row element
rowLine += rowClosing;
// add the current row to the table
table += rowLine;
}
// close the table
table += tableClosing;
return table;
}
Now just use this function for creating a table like so:
document.getElementById("demo").innerHTML = createTable(kvArray);
I know this is not as short as some of the answers given here, but it is much simpler to understand, as you obviously lack some concepts, namely your code was creating in each row and you were lucky it worked.

Returning cell value based on Radio selection

The goal I am trying to achieve is to retrieve a cell value based on a form radio selection and update a text area.
Process: User opens dialog box. They select a field office. Onclick runs the function check. After check runs google.script.run.withSuccessHandler(addSignatureLine).getSignatureLine(cellElement); is supposed to run and update the textarea with the Id 'AdditionalMessage' with the signature line retrieved from .getSignatureLine.
Here are two functions of the html code:
<script>
function addSignatureLine(signatureLine){
document.getElementById('AdditionalMessage').value = '\n\n'signatureLine;
};
function updateSignatureLine() {
var cellElement = document.getElementById('ET');
console.log('cellElement: ' + cellElement);
google.script.run.withSuccessHandler(addSignatureLine)
.getSignatureLine(cellElement);
};
function check() {
var ele = document.getElementsByName('fieldOfficeET');
var flag = 0;
for (var i = 0; i < ele.length; i++) {
if (ele[i].checked)
flag = 1;
}
if (flag == 1)
document.getElementById('Submit').disabled = false;
};
</script>
Here is the getSignatureLine.gs script
function getSignatureLine(cellObject) {
var ss = SpreadsheetApp.openById('googleSheetId');
var sheet = ss.getSheetByName('AMS Contact Information');
var firstRow = 2;
var lastRow = 10;
var dataRange = sheet.getRange(firstRow, 1, lastRow, 11);
var dataValues = dataRange.getValues();
for (var key in cellObject) { //Loop through all the data in the form
Logger.log('key: ' + key);
Logger.log('value: ' + cellObject[key]);
}
//Determines the row the Field Office is in
for (var rr = 0; rr < dataValues.length; rr++) {
if (dataValues[rr][0] == cellObject.fieldOfficeET) {
var r = rr + 2
break;
}
}
var signatureLine = sheet.getRange(r, 11).getValue();
Logger.log("signatureLine: " + signatureLine)
return signatureLine;
}
There is a problem with this line:
document.getElementById('AdditionalMessage').value = '\n\n'signatureLine;
I would try:
document.getElementById('AdditionalMessage').value = '\n\n' + signatureLine;
Add a plus sign to concatenate the text.

Create html table from comma separated strings javascript

I am trying to write a Javascript function which writes the text to (eventually) create the following html tables (I will be passing different length arguments to it to create hundreds of tables):
<table>
<tr><td><u>School</u></td>
<td><u>Percent</u></td>
<tr><td>School 1: </td>
<td>Percent1</td></tr>
<tr><td>School 2: </td>
<td>Percent2</td></tr>
<tr><td>School 3: </td>
<td>Percent3</td></tr>
</table>
The inputs that I have are comma separated strings:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
The function needs to be passed school_list and pct_list, and return a string of the html table code above.
Something like this:
var schoolArr = school_list.split(',');
var pctArr = pct_list.split(',');
var table = "<table>";
for (var i=0; i< schoolArr.length; i++) {
table = table + "<tr><td>"+ schoolArr[i]+"</td><td>"+ pctArr[i] +"</td></tr>";
}
table = table + "</table>";
return table;
You can try below code with Jsfiddle demo ::
function createTable(tab) {
var tar = document.getElementById(tab);
var table = document.createElement('TABLE');
table.border = '1';
var tbdy = document.createElement('TBODY');
table.appendChild(tbdy);
for (var j = 0; j < 4; j++) {
var tr = document.createElement('TR');
tbdy.appendChild(tr);
for (var k = 0; k < 2; k++) {
var td = document.createElement('TD');
td.width = '100';
if (k == 0) td.innerHTML = "School" + (j + 1);
else td.innerHTML = "Percent" + (j + 1);
tr.appendChild(td);
}
}
tar.appendChild(table);
}
createTable('tab');
<div id="tab"></div>
var schools = school_list.split(/,\s*/g).join('</td><td>');
var pcts = pct_list.split(/,\s*/g).join('</td><td>');
return '<table><tr><td>' + schools + '</td></tr><tr><td>' + pcts + '</td></tr></table>'
or a better approach is to construct the whole table in DOM and place it in document directly.
function appendTD(tr, content) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
var table = document.createElement('table');
school_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
pct_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
someParent.appendChild(table);
var numberOfSchools = school_list.split(',');
var numberOfPercent = pct_list.split(',');
var htmlOutput= '<table><tr><td><u>School</u></td><td><u>Percent</u></td>';
for(var i = 0 ; i < numberOfSchools.length; i++)
{
htmlOutput += "<tr><td>" + numberOfSchools[i] + "</td>";
htmlOutput += "<td>"+numberOfPercent[i] +"</td></tr>"
}
htmlOutput += "</table>"
And return htmlOutput
Here's a DOM method, highlighs why innerHTML is so popular. DOM methods are pretty fast in execution lately, but the amount of code is a bit tiresome unless there's a good reason to use it.
The amount of code can be significantly reduced with a couple of helper functions so it is on par with innerHTML methods:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
function makeTable(schools, percents) {
// Turn input strings into arrays
var s = schools.split(',');
var p = percents.split(',');
// Setup DOM elements
var table = document.createElement('table');
var tbody = table.appendChild(document.createElement('tbody'));
var oRow = document.createElement('tr');
var row;
oRow.appendChild(document.createElement('td'));
oRow.appendChild(document.createElement('td'));
table.appendChild(tbody);
// Write header
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode('School'));
row.childNodes[1].appendChild(document.createTextNode('Percent'));
// Write rest of table
for (var i=0, iLen=s.length; i<iLen; i++) {
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode(s[i]));
row.childNodes[1].appendChild(document.createTextNode(p[i]));
}
document.body.appendChild(table);
}
It can be called after the load event, or just placed somewhere suitable in the document:
window.onload = function() {
makeTable(school_list, pct_list);
}

How to Split a dynamic variable into drop down box ( variable seperated by comma)

var device_name = sreeni , murtuza , deepu , bharath , ...... n th number
i need to split this Variable based on the comma and put it in a drop down box.
example:
sreeni
murtuza
deepu
bhatah
Please provide a solution using through Javascript or Jquery
With plain JS,
var device_name = "sreeni , murtuza , deepu , bharath"
var list = device_name.split(/\s*,\s*/);
var dd = document.getElementById("myDropDown");
for(var i = 0; i< list.length; i++){
dd.innerHTML += '<option value="'+list[i]+'">'+list[i]+'</option>';
}
JSFiddle
More Hacky way,
document
.getElementById("myDropDown2")
.innerHTML = device_name
.replace(
/\w+/g,
function(m){
return '<option value="'+m+'">'+m+'</option>'
}
)
.replace(/\s*,\s*/g,'');
var strings = "sreeni,murtuza,deepu,bhatah";
var splitStrings = strings.split();
var selectObj = document.createElement("option");
for (var i in splitStrings) {
selectObj.options[selectObj.options.length] = new Option(splitStrings[i], splitStrings[i]);
}
document.getElementById("idOfElementToContainDropdown").appendChild(selectObj);
var names = device_name.split(",");
var combo = document.getElementById("comboId");
//for i = 1 to length of names list {
var item = document.createElement("OPTION");
item.text=names[i];
combo.options.add(item);
}
Hope this is helpful for you.
var myListOfWords = "apple,orange,bananna,cherries";
var list = myListOfWords.split(",");
var dd = document.getElementById("myDropDown");
for(var i = 0; i< list.length; i++){
var objOption = document.createElement("option");
objOption.text = list[i]
dd.add(objOption) ;
}
//and somewhere in your html
<select id="myDropDown"/>
Here's the working example: dynamic drop down fiddle
With jQuery:
$('#myDropDown').empty();
$.each(device_name.split(","), function(iIndex, sElement) {
if ($.trim(sElement).length > 0) {
$('#myDropDown').append('<option>' + $.trim(sElement) + '</option>');
}
});
Also see this example.

Categories

Resources