Store and get value from one function to another function - javascript

I have a html page and I'm calling a javascript function from the html page and the script is in separate file
HTML
Click Me
<script src="Externalscript.js"></script>
<script>
Initialize('1,2,3,4');
</script>
JavaScript
var myList; //global variable
function Initialize(ids) {
myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
I'm storing the ids value in myList and now I want to retrieve the myList when the button clicked
function ButtonClick() {
alert(myList);
}
Now, when I'm trying to alert the myList it is giving undefined.
How can store the values in a global variable and retrieve in other function

return the value from function than updating global-variable and accessing it
function ButtonClick() {
var returned = Initialize('1,2,3,4');
console.log(returned);
}
function Initialize(ids) {
var myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
return myList;
}
Click Me
Edit: To store the result in global-variable
var returned = Initialize('1,2,3,4');
function ButtonClick() {
console.log(returned);
}
function Initialize(ids) {
var myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
return myList;
}
Click Me

<!DOCTYPE html >
<html>
<head>
<script>
Initialize('1,2,3,4');
var myList; //global variable
function Initialize(ids)
{
myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++)
{
myList.push(idList[i]);
}
}
function ButtonClick()
{
alert(myList);
}
</script>
</head>
<body>
Click Me
</body>
</html>
I just rewrote your code and it prints the list as 1,2,3,4 as expected

I'm having trouble reconstructing the problem. Is this how your code looks like:
Click Me
<script>
var myList; //global variable
function Initialize(ids) {
myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
}
Initialize('1,2,3,4');
</script>
http://codepen.io/calvinclaus/pen/WxNaPX?editors=1011
Because this works...Can you supply a pen with the problem
?

Your code should work.
One advice: split already creates an array: MDN
So what you're doing is:
create an array from a string (idList = ids.split(','))
loop over that array
add every value from that array to a other array (myList.push(idList[i]);)
Where myList = ids.split(','); is enough
Example
var myList;
function Initialize(ids) {
myList = ids.split(',');
}
Initialize('1,2,3,4');
function ButtonClick(e) {
e.preventDefault();
alert(myList);
}
document.getElementById('btn1').addEventListener('click', ButtonClick);
Working demo: fiddle

Related

HtmlService: google.script.run not recognizing gs function

I'm currently trying to pass an array of values from a Google Sheet to the HtmlService where I will have the user choose an option and eventually pass it back to the .gs script. I have been using these two links as references:
1. Google Documentation
2. Stack Overflow example
When running the code, I looked at my console and noticed this error:
VM3051:4 Uncaught TypeError: google.script.run.withSuccessHandler(...).getVersionArray is not a function
It appears that getVersionArray() is not being passed correctly. When removing this function from the rest of that google.script.run call, the error goes away.
Also, per link two, I tried that code with the template and never even got a window to pop up, so I have been using the HtmlOutput example from the Google documentation link as a starting point. I have also tried the code with and without the SandboxMode declaration.
gs code:
function bugPieChart() {
getVersionArray();
openDialog();
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getVersionArray();
});
function buildOptionsList(uniqueArray) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < uniqueArray.length; i++) {
list.append('<option value="' + uniqueArray[i].toLowerCase() + '">' + uniqueArray[i] + '</option>');
}
}
</script>
</head>
<body>
<select id="optionList">
<option>Loading...</option>
</select>
<input type="button" value="Close" onclick="google.script.host.close()" />
</body>
</html>
I think your just missing a closing bracket on the function above it.
function bugPieChart() {
getVersionArray();
openDialog();
}
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}

pushing into arrays in javascript

My script (is meant to) grab text from the a page (which works fine) and then splits it by by newline (\n) and puts each splitted string into an array called "dnaSequence"; from there it loops through each element in the array and if the string contains the character ">" it assigns that string to the "var header_name", else it pushes all other lines into a new array called "dnaSubseq". The original text looks something like this:
>header_1
gctagctagc
cgcgagcgagc
>header_2
gcgcatgcgac
When I execute the code it fails to alert on anything. Here is the code:
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.pushValues(dnaSequence[i]);
}
alert(dnaSubseq);
}
}
Change
dnaSubseq.pushValues(dnaSequence[i]);
To
dnaSubseq.push(dnaSequence[i]);
If it doesn't alert anything, that means you forgot to invoke the function :)
loaderMy();
http://jsfiddle.net/zszyg5qx/
Try this function
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.push(dnaSequence[i]);
}
alert(dnaSubseq);
}
}

I'm adding only the last element to the JS array

Here is my code so far: I am trying to create a new JSON object called dataJSON using properties from the GAJSON object. However, when I try to iterate over the GAJSOn object, I get only its last element to be added to the array.
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":
"3","country":"Spain"},{"bounceRate":"6","country":"Romania"},
{"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},
{"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
Your push of the new object should be within the loop.
for(var i =0; i<GAJSON.data.length; i++) {
viewJSON.data.push({
bounceRate: GAJSON.data[i].bounceRate,
country: GAJSON.data[i].country
});
}
DEMO
You are overwriting values every time at dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
Try this code:
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":"3","country":"Spain"},{"bounceRate":"6","country":"Romania"}, {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"}, {"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON[i] = [];
dataJSON[i]["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON[i]["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
console.log(viewJSON);
DEMO

Selection of multiple values from drop down list

I've a drop down list that contains all the ontacts on mobile. I want to select more than one contact at a time.
When I was working on regular html & JS pages I used this code:
function loopSelected()
{
var txtSelectedValuesObj = document.getElementById('txtContactsName');
var selectedArray = new Array();
var selObj = document.getElementById('AllContacts');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++)
{
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
But when I use it on Android, then if statement is skipped & it just stops,this statement:
"selObj.options[i].selected"
seems strange for the mobile!
This worked:
function ChooseContact(data)
{
var txtSelectedValuesObj = document.getElementById('txtContactsName');
var selectedArray = new Array();
var selObj = document.getElementById('contacts');
var i;
var count = 0;
for(i=0;i<selObj.options.length;i++)
{
if(selObj.options[i].selected==true)
{
selectedArray[count] = selObj.options[i].value;
alert(selObj.options[i].value);
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
I just modified this:
if (selObj.options[i].selected)
to this:
if(selObj.options[i].selected==true)

Continuously loop through JavaScript text array onclick

I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>

Categories

Resources