I have the following code.
var stackMapIn = [];
var stackMapOut = [];
var stackBack = [];
stackMapOut.push("m1");
$scope.clickLinks = function(initialOut,initialIn,extra,backIn,backOut,name){
$('div#'+initialOut+'Map,'+extra).fadeOut('slow',function(){
$('.'+initialOut+'Details,.bkbtn'+backOut).css("display","none");
$('.'+initialIn+'Details,.bkbtn'+backIn).css("display","block");
$('.noQuery').css("display","none");
$("#buildingHeader").html(name);
$('div#'+initialIn+'Map').fadeIn('slow');
})
stackMapOut.push(initialIn);
stackMapIn.push(initialOut);
stackBack.push(backIn);
}
$scope.clickBack = function(bkbtnCheck){
alert(stackBack[0]);
mapOut = stackMapOut.pop();
mapIn = stackMapIn.pop();
stackBack.pop();
backIn = stackBack[0];
alert(backIn);
$('div#'+mapOut+'Map').fadeOut('slow',function(){
$('.'+ mapOut + 'Details,.bkbtn').css("display", "none");
$('.' + mapIn + 'Details,.bkbtn'+backIn).css("display", "block");
$(".noQuery").css("display","none");
$("#buildingHeader").html("Name");
$('div#' + mapIn + 'Map').fadeIn('slow');
})
}
Now I am going to do a quick run-through of what happens as this code runs.
The first time clickLinks runs:
initialIn = 'm2'
initialOut = 'm1'
backIn = 'Home'
clickBack has not run yet.
The second time clickLinks runs:
initialIn = 'm7'
initialOut = 'm2'
backIn = 'CentralPortfolio'
Ok so at this point things should be looking like this (I expect):
stackMapOut = ['m1','m2','m7']
stackMapIn = ['m1','m2']
stackback = ['Home','CentralPortfolio']
Now we run clickBack... Why does the alert output "Home"??
What I am trying to do here is, I have a series of things appearing and disappearing when clickLinks runs. Sometimes, the user can run clickBack in order to return to the previous state(status). So, I am using JavaScript stack to keep track of what state it is on and thus where it needs to return.
The problem is, I can run clickLinks once, clickBack once consecutively without issue. I can even run clickLinks a second time and still click the back button 2 times (to return to start) without issue. But I still don't understand why stackBack[0] (which should be the top of the stack ?) = "Home" at this point instead of "CentralPortfolio".
Because the real problem that I run into is now if I run clickLinks a third time: still stackBack[0] = 'Home' (when I expect it to be 'CentralCampus' at this point) and thus, it is the "Home" back button that is showing (while the correct other stuff is showing in accordance to mapOut and mapIn) instead of CentralPortfolio' back button to be showing; since I have 'CentralCampus' "popped" off before I use it.
Please, if any other information is needed or you need more clarification let me know. I tried my best to provide any needed information and make it as clear as possible.
Now we run clickBack... Why does the alert output "Home"??`
because stackBack[0] is Home. What would you expect it to do? You even have it in your question:
stackback = ['Home','CentralPortfolio']
The index 0 is the first element in your array, which is Home. The last element is stackBack[stackBack.length - 1]
using JavaScript stack
No, you are using a javascript array, but using it like a stack. Except when you index it like an array - which is the root of your confusion. You can use it as a stack with pop and push, but then don't try and index it with []
When you push on an array, you add an element to the end of the array. In other words, it ends up as the last element at the index yourArray.length - 1. When you pop, you take that last element off the array again. So popping stackback would give you back CentralPortfolio, and, of course, the first element is unchanged.
Related
I have written a very simple code on my Google Sheets file. This is the purpose:
Save some cells values from StaticSheet (all the Copyxxx) that need to be copied in DynamicSheet.
Get the value of one specific cell inserted by the user manually.
Enter a While loop useful only to increase an indicator and get the number of the row where I want to copy those values previously saved.
Copy those values on this row but different columns.
The problem is that it seems that most of the time it does not even run the script after I told it to do so.
What is funny is that sometimes it works, super slowly, but it works for like a couple of minutes. And after it stops working again.
Could you please tell me what am I missing here please?
function Copy_Static_on_Dynamic() {
var app = SpreadsheetApp;
var ss = app.openById("xxxxyy--------yyzzzz")
var StaticSheet = ss.getSheetByName("DEAT Price");
var DynamicSheet = ss.getSheetByName("DEAT Price + TEST");
var CopySKU = StaticSheet.getRange(5,1,40);
var CopyPrices = StaticSheet.getRange(5,3,40,4);
var CopyUsage = StaticSheet.getRange(5,8,40);
var Week_1 = StaticSheet.getRange(2,4).getValues();
var i = 1;
Logger.clear();
while(DynamicSheet.getRange(i,3).getValues() != Week_1)
{
Logger.log(i);
i+=1;
}
CopySKU.copyTo(DynamicSheet.getRange(i,4,40));
CopyPrices.copyTo(DynamicSheet.getRange(i,6,40,4));
CopyUsage.copyTo(DynamicSheet.getRange(i,11,40));
}
If you see the "Preparing for Execution" message in the Apps Script editor, you can reload the browser window and run the function again. The program will likely go away.
So I think I have solved it.
As Serge insas was saying I had my script running on the background, I found it out on the "Execution" section, where you can also interrupt them.
After I discover it I kept testing, and I saw that the while loop needed almost 2 seconds to check the condition every time, making the script incredibly long.
So instead of:
while(DynamicSheet.getRange(i,3).getValues() != Week_1)
... I have created a variable declared previously such as:
var WeekLOOP = DynamicSheet.getRange(i,3).getValues();
while(WeekLOOP != Week_1) { --- }
... and now the script needs few milliseconds to run the condition. I don't have enough technical knowledge to say if this was the only issue, but is what apparently solved my problem.
Thanks to all for the support! Will come back if I need any further help :)
As was mentioned by Amit Agarwal, to solve the error message mentioned on the question, refresh the web browser tab.
Regarding the code,
On
var Week_1 = StaticSheet.getRange(2,4).getValues();
and
DynamicSheet.getRange(i,3).getValues()
instead of getValues you should use getValue because your code are referring to single cell cells otherwise you will be getting 2D arrays instead of scalar values.
The use of while should be made very carefully to avoid functions running endlessly. You could add some "safeguard" like the following
var max_iterations = 100 // Edit this
while(DynamicSheet.getRange(i,3).getValue() != Week_1 && i <= max_iterations) {
The following Javascript is hanging up. I've been teaching myself Apps Script to sort data on a sheet. My web developer friend and I have been clueless for the last 2 hours as to why this particular script stalls. It just says Running Script forever....
What is happening is that I have a section of a spreadsheet designated as a calendar area which already has a dynamic calendar printed onto it by one of my other functions. For testing purposes I isolated this function and gave it a dummy array, but the function should loop through the calendar, locate the COORDs of the 'date' i.e. 1,2,3,4th and return the coordinates of an empty cell below that date (the place where i will put data into the calendar).
function printCalendarValues(array){
var array = [0,143,534,342,54,1,41,1];
var Calendar_Display_range = recruiter_sheet.getRange('B8:H19');
var Calendar_Display_values = Calendar_Display_range.getValues();
function getCellBelow(day, rangeArray){
for(i=0; i<rangeArray.length; i++){
for(j=0;j<rangeArray[i].length; j++){
if(rangeArray[i][j]==day){
var res = [i+9,j+2];
return res;
};
};
}
};
for(i=0;i<2;i++){ //< ---- THIS IS WHERE IT BREAKS
// If I take the code in this for loop out of it and run it
// only once then it runs as expected. It breaks when I put it in
// this for loop. You can see I only loop twice right now. I
// did that for testing, but i've tried twice, or array.length
// anything other than running it once breaks it.
var cellBelow = getCellBelow(i+1, Calendar_Display_values);
recruiter_sheet.getRange(cellBelow[0],cellBelow[1]).setValue(array[i]);
};
};
You need to either define the variable i at the top of your function.
function printCalendarValues(array){
var i;//Define i - its' value will be undefined
Or you need to add the var keyword inside the for parameters. for (var i = 0, etc Right now, the variable i is a global. The value of i is in the "global scope." Any function that you run will have access to i as it is right now.
When your second for loop calls the getCellBelow function, both the for loop and the function getCellBelow are sharing the variable i. So, i gets set to 1, then function getCellBelow gets called. Then i gets set back to zero. So your for loop will go on forever. It never gets to 1. It is constantly being set back to zero by the getCellBelow function.
for(i=0;i<2;i++){ //i gets set to zero and then incremented to 1
var cellBelow = getCellBelow(i+1, Calendar_Display_values);//function called
Then in function getCellBelow;
for(i=0; i<rangeArray.length; i++){//i is set to zero and until the array lengh
So, i could easily now be greater than one. And your loop for(i=0;i<2;i++){ will stop.
You can see this by adding Logger.log('i: ' + i) statements, and then viewing the Log. In View menu, choose Logs after running the code.
You should define i inside of the function function getCellBelow(day, rangeArray){
Should be:
function getCellBelow(day, rangeArray){
var i;
So, the usage of i inside that function will be confined to the function and not affect any other value of i outside of that function.
Important: Even though this could probably be done with php (I'm using WooCommerce on Wordpress), I want this script to run only on my browser. That's why I want to do it in Javascript. Hence, I'm using Custom Javascript for Websites to load my script from my browser.
What my script should do: Check if the data of a specific element has been changed.
Logic: Step 1) Get and locally remember specific string (order number) of a specific class. Step 2) Refresh the page. Step 3) Again get the specific string (order number) of a specific class. Step 4) If strings do not match, run a function (play an audio).
Problem: After page reloads, the script starts to run again from the beginning. Hence, it results in overriding the stored string. As a result, stored and newly fetched string are always equal.
Question: How do I make the script to run the 3rd step only after refresh so that the stored data doesn't override itself?
Current code:
var OrderIdOld = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var x = (OrderIdOld[0].innerText); // Get the string of the first element of the class "row-title"
var compareOld = x.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
localStorage.setItem("compareOld", compareOld); // Store this element in local storage, so that it can be used after page reloads.
setInterval ("window.location.reload()", 30000); // Reload page every 30 secs.
var remembered = localStorage.getItem("compareOld"); // Assign stored element to a new var.
var n = compareOld.valueOf(); // Turn stored element into a number (for easy comparison later).
var OrderIdNew = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var y = (OrderIdNew[0].innerText); // Get the string of the first element of the class "row-title"
var compareNew = y.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
var m = compareNew.valueOf(); // Turn fetched element into a number (for easy comparison later).
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHz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BXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
} // Function that will play the sound.
if (n!=m) {
beep();
} // Run function if two numbers are not equal.
Additional: I have gathered the parts of the code from various Questions on stackoverflow. Meaning, I have been searching about this topic for the past week. This is my first questions ever. Hopefully I formatted the question so that it easy to understand.
EDIT: The issue has been solved. I used the idea of only running the first step of function on the first load of page. This post helped me to get functionality working https://stackoverflow.com/a/22334768/7929506
The working code looks like this:
function beep() {
window.open('https://www.youtube.com/watch?v=EQ3zPIj2O5k','_blank');
}
if (sessionStorage.getItem("visit") == null) {
var OrderIdOld = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
sessionStorage.setItem("OrderIdOld", OrderIdOld);
sessionStorage.setItem("visit", new Date());
setTimeout("window.location.reload()", 10000);
}
else {
var OrderIdNew = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
var x = sessionStorage.getItem("OrderIdOld");
if (x==OrderIdNew) {
setTimeout("window.location.reload()", 10000);
}
else {
beep();
var x = sessionStorage.getItem("OrderIdOld");
sessionStorage.removeItem("OrderIdOld");
sessionStorage.removeItem("visit");
setTimeout("window.location.reload()", 10000);
}
}
When you refresh the page first time, you can simply append a flag variable to URL to identify weather its a refresh or a first time load. Based on that, you can pass a localized variable to script and if that is set then you need to refresh else not.
I actually just spent a really long time figuring out answers to this question by piecing it together from the spotty documentation and a lot of web console inspection. Since by far the most useful information came from Stack Overflow, I wanted to put this question, and its answer, here for the future benefit of anyone else searching.
The question is, how can you add javascript to a question that will immediately save that question's answer into an embedded data field? Immediately, as in, not waiting until the next Qualtrics.SurveyEngine.AddOnLoad(). This involves the sub-question of how can you add javascript to a survey question and have it run when the Next button is clicked? And the sub-question of, how can you save embedded data fields that are dynamically named based on the question ID?
Caveat Emptor: all this javascript hacking is not explicitly supported by Qualtrics, so the code here may stop working eventually.
Here is how to get the response value of a slider and save it in an embedded data field with a name that is numbered based on the question ID. This way only works if the text input box for the slider is visible. There's probably a way to do it without that, too, maybe someone else can add that to the answers.
Qualtrics.SurveyEngine.addOnload(function()
{
// everything here runs when the page is loaded. So, we can get the Question ID here,
// but we can't get the response value until later.
var currentQuestionID = this.getQuestionInfo().QuestionID
//var resultEmbeddedName = currentQuestionID + "_result" //e.g. QID6_result
var resultEmbeddedName = "result_" + currentQuestionID.substring(3) //e.g. result_6
$('NextButton').onclick = function (event) {
// everything in here will run when you click the next button
// note that it has access to javascript variables from the enclosing function
// however, if you declare something in here with "var" then it will be a LOCAL variable
// the following alert will appear when you click the next button. For me, it appears twice;
// I'm not sure why.
// Save the current question's response value
var responseTextField = document.getElementById(currentQuestionID + '~1~result')
var currentResponse = responseTextField.value
alert("Result: " + currentResponse + "\nwill be available to future questions as: \n$" + "{e://Field/" + resultEmbeddedName + "}")
Qualtrics.SurveyEngine.setEmbeddedData(resultEmbeddedName, currentResponse)
// and now run the event that the normal next button is supposed to do
Qualtrics.SurveyEngine.navClick(event, 'NextButton')
}
});
For multiple choice items, it's a bit more complicated. Here's the code that works, with lots of comments and demos. Note that the variable "currentResponse" ends up holding the NUMBER of the chosen choice, while "currentChoiceText" ends up holding the text label for that choice (e.g. Yes or No.) So you can save whichever one you prefer.
Qualtrics.SurveyEngine.addOnload(function()
{
// everything here runs when the page is loaded. So, we can get the Question ID here,
// but we can't get the response value until later.
var currentQuestionID = this.getQuestionInfo().QuestionID
console.log("Current Question ID is: " + currentQuestionID)
//var resultEmbeddedName = currentQuestionID + "_result" //e.g. QID6_result
var resultEmbeddedName = "result_" + currentQuestionID.substring(3) //e.g. result_6
$('NextButton').onclick = function (event) {
// everything in here will run when you click the next button
// note that it has access to javascript variables from the enclosing function
// however, if you declare something in here with "var" then it will be a LOCAL variable
// the following alerts will appear when you click the next button. For me, it appears twice;
// I'm not sure why.
// Save the current question's response value
var questionObject = Qualtrics.SurveyEngine.getInstance(currentQuestionID)
var currentResponse = questionObject.getSelectedChoices()[0] //in case more than one is selected, it will only work here to take one!
var theQuestionInfo=questionObject.getQuestionInfo()
var choicesObject=theQuestionInfo.Choices
var thisChoiceObject=choicesObject[currentResponse]
var currentChoiceText=thisChoiceObject.Text
console.log("Number of the current choice is " + currentResponse)
console.log("Text of the current choice is " + currentChoiceText)
alert("Result: " + currentChoiceText + "\nwill be available to future questions as: \n$" + "{e://Field/" + resultEmbeddedName + "}")
Qualtrics.SurveyEngine.setEmbeddedData(resultEmbeddedName, currentChoiceText)
// and now run the event that the normal next button is supposed to do
Qualtrics.SurveyEngine.navClick(event, 'NextButton')
}
});
Both of these refer to the question ID dynamically, so they will work individually if you copy the question to a new one. Without needing to change any of the javascript code.
To test these, make a slider question or a multiple choice question and add the respective javascript. Then, make another slide after a page break (the page break is necessary to cause the appearance of the Next button). In that slide, put a piped text field like ${e://Field/result_1} or whatever the alert dialog tells you the saved value will be. When you preview the survey, you should see the value that was entered on the first question, in the piped text field of the second question.
As far as this demo goes, you could certainly achieve the same effect with just piped text. But if you have some reason that you want a question to actually immediately save its response into embedded data, this will do that for you.
Also, if you need to know how to run code when the Next button is clicked, this can be adapted for any general need for that.
I was having problems that calling the below code in the $('NextButton').onclick method was forcing $('NextButton').onclick method to be called twice. Removing it worked for me so the onclick method gets called only once but still moves the survey forward.
// and now run the event that the normal next button is supposed to do
Qualtrics.SurveyEngine.navClick(event, 'NextButton')
This works each time you press the "Next" button. Hope that helps!
Qualtrics.SurveyEngine.addOnload(function(){
var nextButton =document.getElementById("NextButton");
if (nextButton!=null){
$("NextButton").on("click", function(event) {
alert("Hello World!");
});
}
});
I've been programming in javascript (with a support from jquery) and I've run into some weird variable behaviour, which in I think is truly unexpected (or maybe I don't know something).
Basically, what I wanna do is to have one variable (zodziai) (array) be "stuffed" with arrays in one part of code and later on have those arrays removed by a click of buttons (one by one).
Also I still want to have those arrays saved in the end of the game even if the first variable is empty because of the button clicks.Easy, I thought to myself, so I've created another array variable (zodziai2) and equated those both in the beginning of the game (when the first one is full of arrays, ready to have them removed one by one.
Everything seems to fine until I check the value of zodziai2, second variable, in the end of the game. Even if it hasn't been touched throughout the process of removing elements from zodziai (first variable), somehow it turns out to be empty too in the end of the game.
Code: I declared both variable inside document.ready as = [];
$("#begin").click(function() {
//#begin is a button which starts the game
$("#enterwords").html("It's showtime!");
zodziai2 = zodziai; //zodziai is full of stuff, making zodziai2 the same
alert(window.zodziai2); //checking, zodziai2 seems to be equal to zodziai
taskai = 0;
maxtaskai = zodziai.length;
...
if (zodziai.length > 0) {
... stuff, just DOM.
...
}
});
And there goes the next button, which is responsible for removing one item from zodziai array. Somehow it gets removed from zodziai2 too.
$("#next").click(function() {
enword = $("#angliskas_zodis").val();
ltword = $("#lietuviskas_zodis").val();
//enword = enword.split("");
//atitinkamas = atitinkamas.split("");
if (enword == atitinkamas) {
...
zodziai.remove(random_skaicius); // removing one item from zodziai (no worries, it's a self written function, working as a bee
...
...
});
Later on, I define the third button, restart, in which zodziai2 is now empty as is zodziai. How can zodziai2 be empty if the code is only "playing" with zodziai? What am I missing??
$("#restart").click(function() {
zodziai = zodziai2; //should be full of stuff, but is certainly not :(
random_skaicius = 0;
ilgis = 0;
zodis = "";
atitinkamas = "";
tempzodislt = "";
taskai = 0;
maxtaskai = 0;
klaidingi = [];
$("#angliskas_zodis").val("");
$("#lietuviskas_zodis").val("");
surasymas(window.zodziai2);
alertify.alert("Drop us a line if you think this function would be useful :)");
});
Just a pointer. I see you write a statement zodziai2 = zodziai. What it means that both variables point to the same memory location of the array. If you remove an element from zodziai, it'll be removed from zodziai2 too. Does this helps?