return every value from for loop? - javascript

I'm trying to return every value from the array allArtistsArray, which gets values from a spreadsheet, and have them display as an unordered list with buttonTemplate first, and then every value in the spreadsheet after it.
The problem I'm having is that only the first value from the spreadsheet is being returned and displayed on the web app. How do I get every value to display after buttonTemplate?
What's being displayed is:
* buttonTemplate
or
* value 1 from spreadsheet
What I'm trying to get displayed is:
* buttonTemplate
* value 1 from spreadsheet
* value 2 from spreadsheet
* value 3 from spreadsheet
* etc
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= getContent("js") ?>
<?!= getContent("css") ?>
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Abel">
</head>
<body>
<div id="artistTabs">
<ul id="artistList">
<?!= createArtistList(); ?>
</ul>
</div>
</body>
</html>
code.gs
var ss = SpreadsheetApp.openById('id');
var sheet = ss.getSheets()[0];
function doGet()
{
return HtmlService.createTemplateFromFile('index').evaluate();
}
function getContent(filename)
{
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function createArtistList()
{
var buttonStartingRow = 2;
var buttonStartingColumn = 1;
var buttonCell = sheet.getRange(buttonStartingRow, buttonStartingColumn).getValue();
var x = '<li><a onClick="addArtist(); return false;" href="">';
var y = buttonCell;
var z = '</a></li>';
var buttonTemplate = x + y + z;
//return buttonTemplate;
var startingRow = 2;
var startingColumn = 1;
var howManyRows = sheet.getLastRow() - 1;
var howManyColumns = 1;
var allArtistsArray = sheet.getRange(startingRow, startingColumn, howManyRows, howManyColumns).getValues(); //get every name in 1st column after second row
//allArtistsArray = allArtistsArray.filter(function(n){return n[0] !== '' && n[0] !== buttonCell}); //filter 'buttonCell' value and blank rows
//allArtistsArray = allArtistsArray.toString().split(","); //flatten 2d array to 1d array
//Logger.log(allArtistsArray);
for (i = 0; i < allArtistsArray.length; i++)
{
allArtistsArray = allArtistsArray.filter(function(n){return n[0] !== '' && n[0] !== buttonCell}); //filter 'buttonCell' value and blank rows
allArtistsArray = allArtistsArray.toString().split(","); //flatten 2d array to 1d array
if (allArtistsArray == '')
{
Logger.log("array = blank");
break; //leave for loop and only return buttonTemplate ???
}
else
{
var x1 = '<li><a onClick="test(); return false;" href="">';
var z1 = '</a></li>';
var _1 = allArtistsArray[i];
var _2 = x1 + _1 + z1;
Logger.log(_2);
}
}
Logger.log(allArtistsArray);
return buttonTemplate;
}

Looks to me like you should be changing the value of buttonTemplate IN your for loop if that is the result you want. For example: buttonTemplate += _2 (or whatever you want appended it is unclear from your example).
EDIT
Without a snippet to play around with it's hard to see if this works but here is a better example of what I meant:
function createArtistList()
{
var buttonStartingRow = 2;
var buttonStartingColumn = 1;
var buttonCell = sheet.getRange(buttonStartingRow, buttonStartingColumn).getValue();
var x = '<li><a onClick="addArtist(); return false;" href="">';
var y = buttonCell;
var z = '</a></li>';
var buttonTemplate = x + y + z;
var artistsOutput = '';
//return buttonTemplate;
var startingRow = 2;
var startingColumn = 1;
var howManyRows = sheet.getLastRow() - 1;
var howManyColumns = 1;
var allArtistsArray = sheet.getRange(startingRow, startingColumn, howManyRows, howManyColumns).getValues(); //get every name in 1st column after second row
//allArtistsArray = allArtistsArray.filter(function(n){return n[0] !== '' && n[0] !== buttonCell}); //filter 'buttonCell' value and blank rows
//allArtistsArray = allArtistsArray.toString().split(","); //flatten 2d array to 1d array
//Logger.log(allArtistsArray);
for (i = 0; i < allArtistsArray.length; i++)
{
allArtistsArray = allArtistsArray.filter(function(n){return n[0] !== '' && n[0] !== buttonCell}); //filter 'buttonCell' value and blank rows
allArtistsArray = allArtistsArray.toString().split(","); //flatten 2d array to 1d array
if (allArtistsArray == '')
{
Logger.log("array = blank");
break; //leave for loop and only return buttonTemplate ???
}
else
{
var x1 = '<li><a onClick="test(); return false;" href="">';
var z1 = '</a></li>';
var _1 = allArtistsArray[i];
if (_1 != null)
{
var _2 = x1 + _1 + z1;
artistsOutput += _2;
Logger.log(_2);
} else {
Logger.log('The ' + i + 'th element was null for some reason');
}
}
}
Logger.log(allArtistsArray);
return buttonTemplate + artistsOutput;
}

Related

Calling server function onclick and returning templated html

I'm trying to call the getArtistName() function from the code.gs file every time i click the '+' button from the var buttonTemplate in the createArtistList() function.
What it does right now is:
when the var buttonTemplate = '<li><a onClick="addArtist(); return false;" href="">buttonCell</a></li>'; gets clicked on the web app, it runs the addArtist() function in the js.html file
which then calls the writeArtistName() function in the code.gs file, and writes the value that was inputted into the prompt into the spreadsheet.
I need it to also call the getArtistName() function in the code.gs file so i can update the web app with the value that was just inputted into the spreadsheet.
Does google apps script support real time updating like that?
Is there a way to call 2 functions simultaneously from google.script.run?
Example:
google.script.run
.withSuccessHandler(writeSuccess(artistName))
.withFailureHandler(writeFailure)
.writeArtistName(artistName);
Add something like this - .writeArtistName(artistName), .getArtistName();?
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= getContent("js") ?>
<?!= getContent("css") ?>
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Abel">
</head>
<body>
<!-- //nav tabs// -->
<div id="artistTabs">
<ul id="artistList">
<?!= createArtistList(); ?>
</ul>
</div>
</body>
</html>
js.html:
<script>
function addArtist()
{
var artistName = prompt("enter artist whole first name and initial of last name");
if (artistName === "") //user pressed 'ok' but input field was empty
{
return;
}
else if (artistName != "" && artistName !== null) //user inputs something and hits 'ok'
{
google.script.run
.withSuccessHandler(writeSuccess(artistName))
.withFailureHandler(writeFailure)
.writeArtistName(artistName);
}
else //user hits 'cancel' or 'x'
{
return;
}
}
function writeSuccess(artistName)
{
console.log("write success: " + artistName);
}
function writeFailure()
{
console.log("write failure - email myself why it failed and the time it failed");
}
function test()
{
console.log("test"); //open this artists spreadsheet
}
</script>
code.gs:
var ss = SpreadsheetApp.openById('id');
var sheet = ss.getSheets()[0];
function doGet()
{
return HtmlService.createTemplateFromFile('index').evaluate();
}
function getContent(filename)
{
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function createArtistList()
{
//button
var buttonStartingRow = 2;
var buttonStartingColumn = 1;
var buttonCell = sheet.getRange(buttonStartingRow, buttonStartingColumn).getValue();
var x = '<li><a onClick="addArtist(); return false; return getArtistName();" href="">';
var y = buttonCell;
var z = '</a></li>';
var buttonTemplate = x + y + z;
//artist names
var artistsOutput = '';
var startingRow = 2;
var startingColumn = 1;
var howManyRows = sheet.getLastRow() - 1;
var howManyColumns = 1;
var allArtistsArray = sheet.getRange(startingRow, startingColumn, howManyRows, howManyColumns).getValues(); //get every name in 1st column after second row
for (i = 0; i < allArtistsArray.length; i++)
{
allArtistsArray = allArtistsArray.filter(function(n){return n[0] !== '' && n[0] !== buttonCell}); //filter 'buttonCell' value and blank rows
allArtistsArray = allArtistsArray.toString().split(","); //flatten 2d array to 1d array
if (allArtistsArray == '')
{
Logger.log("array = blank");
return buttonTemplate;
break; //leave loop and only return 'buttonTemplate'
}
else
{
var x1 = '<li><a onClick="test(); return false;" href="">';
var z1 = '</a></li>';
var _1 = allArtistsArray[i];
var _2 = x1 + _1 + z1;
artistsOutput += _2
}
}
return buttonTemplate + artistsOutput; //return 'buttonTemplate' and every value from spreadsheet that is not blank
}
function writeArtistName(artistName)
{
var lastRow = sheet.getLastRow() + 1; //gets next unused row
var column = 1; //first column
var lastCell = sheet.getRange(lastRow, column);
lastCell.setValue(artistName); //sets next blank row as artistName
}
function getArtistName()
{
var lastRow = sheet.getLastRow(); //gets last row with content
var column = 1;
var lastArtist = sheet.getRange(lastRow, column).getValue(); //gets last row with artistName
//Logger.log(lastArtist);
var x = '<li><a onClick="test(); return false;" href="#">';
var y = lastArtist;
var z = '</a></li>';
var xyz = x + y + z;
Logger.log(xyz);
return xyz;
}
//figure out how to call getArtistName() from buttonTemplate onClick
//and have the artist name from last row return and display in the list
Is there a good reason you can't have a single server function that does both?
So something like:
function writeAndGetArtistName(artistName)
{
writeArtistName(artistName);
return getArtistName();
}
Then your client code would just call this one function.
Though if I'm understanding what you're trying to do here, and your getArtistName function is just getting the same artistName that writeArtistName just added to the spreadsheet, it might be easier to just pass artistName to getArtistName and then you get to skip these three lines of code:
var lastRow = sheet.getLastRow(); //gets last row with content
var column = 1;
var lastArtist = sheet.getRange(lastRow, column).getValue(); //gets last row with artistName

How to dynamically create buttons based on random conditions

I have created a button using JavaScript, and I have a list that is supposed to get a random number when I "roll the dice"
I need to list of numbers to say "You rolled a 1" for example. How do I do that? And also I only need it to show the last 10 numbers.
var rollNumber = 0;
var values = [];
function dieRolled() {
rollNumber += 1;
var numRolled = Math.ceil(Math.random() * 6);
values.push(numRolled);
document.getElementById("results").innerHTML = "";
for (var x = values.length-1 ; x>=0; x--) {
var newRoll = document.createElement("li");
newRoll.innerHTML = values [x] +"You rolled a";
document.getElementById("results").appendChild(newRoll);
if (x == 11)break;
}
}
How about this?
var output = document.getElementById("Output");
var values = [];
function roll()
{
values.push(Math.ceil(Math.random() * 6));
// If the history is too big, drop the oldest...
if (values.length > 10)
{
values.shift();
}
// Rewriting the history log
var text = "";
for (var i in values)
{
text += "You rolled a " + values[i] + "\n";
}
output.innerHTML = text;
}
// Rolling multiple times
setInterval(function(){ roll(); }, 1000);
<pre id="Output"></pre>
Try this:
var list = document.getElementById('demo');
var count = 0;
function changeText2() {
count++;
if(count <= 10)
{
var numRolled = Math.ceil(Math.random() * 6);
var entry = document.createElement('li');
entry.appendChild(document.createTextNode("You rolled:"+numRolled));
list.appendChild(entry);
}
}
<input type='button' onclick='changeText2()' value='Submit' />
<p>Dices you rolled</p>
<ol id="demo"></ol>

javascript error - node was not found : replaceChild

I am trying to swap two array in javascript. While the replacement comes to the last iteration, I am getting "NotFoundError: Node was not found" in the call of parent.replaceChild(item2,item1). Please help me what mistake I have committed.
function sortTable(col){
if($("loacte-resultsTable") == null || $("loacte-resultsTable") == undefined){
return false;
}
if (lastSort == col) {
// sorting on same column twice = reverse sort order
absOrder ? absOrder = false : absOrder = true
}
else{
absOrder = true
}
lastSort = col;
try{
var loacteResultsTable = $("loacte-resultsTable").getElementsByTagName("TBODY")[0];
var loacteResultsTableTR = loacteResultsTable.getElementsByTagName("TR");
allTR = loacteResultsTableTR;
} catch (e) {
return false;
}
// allTR now holds all the rows in the dataTable
totalRows = allTR.length;
colToSort = new Array(); //holds all the cells in the column to sort
colArr = new Array(); //holds all the rows that correspond to the sort cell
copyArr = new Array(); //holds an original copy of the sort data to match to colArr
resultArr = new Array(); //holds the output
allNums = true
allDates = true
//store the original data
//remember that the first row - [0] - has column headings
//so start with the second row - [1]
//and load the contents of the cell into the array that will be sorted
for (x=0; x < totalRows; x++){
var data = setDataType(allTR[x].childNodes[col].innerText);
if(typeof data!="undefined"){
colToSort[x] = setDataType(allTR[x].childNodes[col].innerText);
}else{
colToSort[x] = setDataType(allTR[x].childNodes[col].textContent);
}
colArr[x] = allTR[x];
}
//make a copy of the original
for (x=0; x<colToSort.length; x++){
copyArr[x] = colToSort[x];
}
//sort the original data based on data type
if (allNums){
colToSort.sort(numberOrder);
} else if (allDates){
colToSort.sort(dateOrder);
} else {
colToSort.sort(textOrder);
}
//match copy to sorted
for(x=0; x<colToSort.length; x++) {
for(y=0; y<copyArr.length; y++) {
if (colToSort[x] == copyArr[y]) {
boolListed = false
//search the ouput array to make sure not to use duplicate rows
for(z=0; z<resultArr.length; z++) {
if (resultArr[z]==y) {
boolListed = true
break;
}
}
if (!boolListed){
resultArr[x] = y
break;
}
}
}
}
//now display the results - it is as simple as swapping rows
for (x=0; x<resultArr.length; x++) {
//allTR[x].swapNode(colArr[resultArr[x]])
swapNodes(allTR[x],colArr[resultArr[x]]);
}
function swapNodes(item1,item2)
{
var itemtmp = item1.cloneNode(1);
var parent = item1.parentNode;
item2 = parent.replaceChild(itemtmp,item2);
parent.replaceChild(item2,item1);
parent.replaceChild(item1,itemtmp);
itemtmp = null;
}
}
The call to the sortTable method is from synch().This is the UI part coded in JS:
function synch(){
var loacteResults = $('loacte-results');
var loacteResultsTable = $('loacte-resultsTable');
tab = loacteResults.getElementsByTagName('TABLE')[0];
loacteResults.removeChild(tab);
var updatedResults =
'<table id="loacte-resultsTable" cellspacing="0" cellpadding="3" border="1">' +
'<thead class="thead">' +
'<tr>' +
'<th>Site ID</th>' +
'<th>Store Name</th>' +
'<th>Agent Code</th>' +
'<th>Address</th>' +
'<th>City, State</th>' +
'<th>Phone</th>' +
'<th>Hours</th>' +
'<th>Deleted</th>' +
'<th width="65px;">Priority <img src="images/sort_up_down.gif" onclick="javascript:sortTable(8)" style="cursor: pointer;"/></th>' +
'<th width="115px;">Est.Dist.(miles) <img src="images/sort_up_down.gif" onclick="javascript:sortTable(9)" style="cursor: pointer;"/></th>' +
'</tr>' +
'</thead>' ;
if(tr == '')
updatedResults = updatedResults + '<tbody><tr><td colspan="10">No Stores to display</td></tr></tbody></table>';
else
updatedResults = updatedResults + '<tbody>' + tr + '</tbody></table>';
loacteResults.innerHTML = updatedResults;
}
In the third parent.replaceChild line item1 is no longer is on the page, since it has been replaced with item2.
Your code broken down:
function swapNodes(item1,item2)
{
var itemtmp = item1.cloneNode(1); //create a copy of item 1
var parent = item1.parentNode; //set a reference to the parent
item2 = parent.replaceChild(itemtmp,item2); //replace item2 with the copy of item1 and store the old child in item2
parent.replaceChild(item2,item1); //replace item1 with item2
parent.replaceChild(item1,itemtmp); //this line is redundant. <-- item1 no longer is on the page.
itemtmp = null;
}

how to show minus currency in brackets with currency sign

I have variable which is negative numbers after $ sign (actually it shows currency with currency sign). Please tell me how to show minus currency in brackets with currency sign. I mean to say how to change var val=($125,220,328.00)
My code is looks like this
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function netAmount(){
var net_amount =0;
$('#productList tr:gt(1)').each(function() {
var row_index= $(this).index();
var qty= $('#productList tr:eq('+row_index+') td input[name="quantity"]').val().replace( /[^0-9\.]/g, '' );
var price= $('#productList tr:eq('+row_index+') td input[name="purchase_price"]').val().replace( /[^0-9\.]/g, '' );
net_amount+= +(parseFloat(qty*price).toFixed(2));
$('input[name="net_ammount"]').val('$'+ addCommas(parseFloat(net_amount).toFixed(2)));
});
}
Now i want if net_amount is looks like -123225.32 then it show in input[name="net_ammount"] as ($123,225.32)
Here's my working attempt:
function addCommas(val2) {
val2 = val2.toString(); // cast to a string
// index of minus sign
var negative = val2.indexOf('-');
// org = original index of dot, make val an array; i should be above index of minus + 1; decrease i
for (var i = org = val2.indexOf('.'), val2 = val2.split(""); i > negative + 1; i--) {
// i difference between org and i is multiple of 3 and at the current index is a number
if ((org - i) % 3 == 0 &&
/[0-9]/.test(val2[org - i])) {
// insert a `,` and decrease i
val2.splice(i--, 0, ',');
}
}
val2 = val2.join("");
if(parseInt(val2, 10) >= 0)
return '$' + val2;
else
return '($' + val2 + ')';
}
alert(addCommas(123225.32)); // $123,225.32
alert(addCommas(-123225.32)); // ($123,225.32)
function remCommas(val){
var pre = '';
if(val.indexOf("(") > -1){
pre = "$-";
val = val.replace(/\(\$/, "").replace(/\)/, "");
}
val = pre + val;
return val;
}
alert(remCommas('$123,225.32')); // $123,225.32
alert(remCommas('($123,225.32)')); // $-123,225.32

JavaScript Tag Cloud with IBM Cognos - IE is null or not an object

I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:
"Message: '1' is null or not an object"
The line of code where this is present is 225 which is:
var B = b[1].toLowerCase();
I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:
<script>
// JavaScript Document
// ====================================
// params that might need changin.
// DON'T forget to include a drill url in the href section below (see ###) if you want this report to be drillable
var delimit = "|";
var subdelimit = "[]"; // change this as needed (ex: Smith, Michael[]$500,000.00|)
var labelColumnNumber = 0; // first column is 0
var valueColumnNumber = 1;
var columnCount = 2; // how many columns are there in the list?
// ====================================
/*
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return ( num );
}
function filterNum(str) {
re = /\$|,|#|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|/g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}
table = document.getElementById("dg");
if ( table.style.visibility != 'hidden'){ //only for visible
/*alert('Visible');*/
tags = document.getElementById("dg").getElementsByTagName("SPAN");
txt = "";
var newText = "a";
for (var i=columnCount; i<tags.length; i++) {
/*
valu = filterNum(tags[i+valueColumnNumber].innerHTML);
txt += valu;
txt += subdelimit+tags[i+labelColumnNumber].innerHTML+delimit;
i = i+columnCount;
*/
if(i%2!=0){
var newValue = filterNum(tags[i].innerHTML);
}else var newName =tags[i].innerHTML;
if((i>2) & (i%2!=0)){
newText = newText+newValue+subdelimit+newName+delimit;
if(typeof newText != 'undefined'){
txt = newText;
txt = txt.substr(9);
/* alert(txt);*/
}
}
}
}/*else alert ('Hidden');*/
function getFontSize(min,max,val) {
return Math.round((150.0*(1.0+(1.5*val-max/2)/max)));
}
function generateCloud(txt) {
//var txt = "48.1[]Google|28.1[]Yahoo!|10.5[]Live/MSN|4.9[]Ask|5[]AOL";
var logarithmic = false;
var lines = txt.split(delimit);
var min = 10000000000;
var max = 0;
for(var i=0;i<lines.length;i++) {
var line = lines[i];
var data = line.split(subdelimit);
if(data.length != 2) {
lines.splice(i,1);
continue;
}
data[0] = parseFloat(data[0]);
lines[i] = data;
if(data[0] > max)
max = data[0];
if(data[0] < min)
min = data[0];
}lines.sort(function (a,b) {
var A = a[1].toLowerCase();
var B = b[1].toLowerCase();
return A>B ? 1 : (A<B ? -1 : 0);
});
var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
if(logarithmic) {
max = Math.log(max);
min = Math.log(min);
}
for(var i=0;i<lines.length;i++) {
var val = lines[i][0];
if(logarithmic) val = Math.log(val);
var fsize = getFontSize(min,max,val);
dollar = formatCurrency(lines[i][0]);
html += " <a href='###Some drillthrough url which includes the param "+lines[i][1]+"' style='font-size:"+fsize+"%;' title='"+dollar+"'>"+lines[i][1]+"</a> ";
}
html += "</div>";
var cloud = document.getElementById("cloud");
cloud.innerHTML = html;
var cloudhtml = document.getElementById("cloudhtml");
cloudhtml.value = html;
}
function setClass(layer,cls) {
layer.setAttribute("class",cls);
layer.setAttribute("className",cls);
}
function show(display) {
var cloud = document.getElementById("cloud");
var cloudhtml = document.getElementById("cloudhtml");if(display == "cloud") {
setClass(cloud,"visible");
setClass(cloudhtml,"hidden");
}
else if(display == "html") {
setClass(cloud,"hidden");
setClass(cloudhtml,"visible");
}
}
generateCloud(txt);
</script>
Any help or explanations is much appreciated
Sorry, I'm not seeing where a[] and b[] are defined, is this done elsewhere? Firefox and IE may be responding differently to the problem of an undefined array.

Categories