Get the value of multiple input texts with Actionscript 3 - javascript

I'm trying to create a ActionScript application to calculate the volume of sand a mining company can extract off a river. So I got in the stage like 4 input texts named as "WidthOne", "WidthTwo", "WidthThree" and "WidthFour" and other 4 inputs, "HeightOne" ... "Height Four". The mathmatics goes like "WidthOne × HeightOne" ... "WidthFour × HeightFour" and the results go to dynamic fields named "ResultOne" ... "ResultFour".
Is there any way to use a loop to get the value of these fields so I don't need to do it all manually as I need to create other input texts in the stage? I got a working one in HTML and Javascript and basically it is like:
for(i=0;i<=3;i ++) {
var WidthInputID = ['WidthOne','WidthTwo','WidthThree','WidthFour'];
var HeightInputID = ['HeightOne','HeightTwo','HeightThree','HeightFour'];
var ResultsInputID = ['ResultOne','ResultTwo','ResultThree','ResultFour'];
var Width = document.getElementById(WidthInputID[i]).value;
var Height = document.getElementById(HeightInputID[i]).value;
var Result = document.getElementById(ResultsInputID[i]).value = Width*Height;
}
I don't know if I made myself clear because my English is bad, so I'm sorry if I'm not clear.

var widthInputID:Array = ['WidthOne','WidthTwo','WidthThree','WidthFour'];
var heightInputID:Array = ['HeightOne','HeightTwo','HeightThree','HeightFour'];
var resultsInputID:Array = ['ResultOne','ResultTwo','ResultThree','ResultFour'];
for(i = 0; i <= 3; i++) {
var width:Number = Number(this[widthInputID[i]].text);
var height:Number = Number(this[heightInputID[i]].text);
var result:Number = width*height;
this[resultsInputID[i]].text = result;
}

You could follow the same strategy in AS3. The main differences would be:
To access an element on the stage, instead of document.getElementById("elementId") you would use:
this["instanceName"]
The property name for the content of the text field isn't value. The property is called text.

Related

Google App Scripts find text in spreadsheet and return location index

I am a novice here to google app scripts and my JavaScript is also not very strong, but neither of these seem to be the problem here as my code works the first time I run it but then when I try to call it again it fails.
Simply I am trying to have a function that will dynamically find a given text in a given range. While it looks like there might be a built in package that does this I cannot figure out how to implement it. And the documentation is not helpful for someone new.
Option 1: was to implement the following: https://developers.google.com/apps-script/reference/spreadsheet/text-finder#findAll()
Since that has not been sucessful in finding out how to do it I moved to creating the following simple two functions, Option 2:
function findIndexRow(range,fText){
for(var i = 0; i<range.length;i++){
for(var j = 0; j<range.length;j++){
if(range[i][j] == fText){
var fTextRow = i+1;
var fTextCol = j+1;
}
}
}
return fTextRow
}
function findIndexCol(range,fText){
for(var i = 0; i<range.length;i++){
for(var j = 0; j<range.length;j++){
if(range[i][j] == fText){
var fTextRow = i+1;
var fTextCol = j+1;
}
}
}
return fTextCol
}
It takes in a range that I defined like:
var sheet = SpreadsheetApp.openById('the-gsheet-id');
var CurrSheet = sheet.getSheetByName('Sheet1');
var SHTvalues = CurrSheet.getDataRange().getValues();
So the above works when I call it once in my main code but the second time it returns null, help here as to why re calling the same function does not work.
var text1Row = findIndexRow(SHTvalues,"text1");
var text1Col = findIndexCol(SHTvalues,"text1");
Logger.log(text1Row)
Logger.log(text1Col)
var text2Row = findIndexRow(SHTvalues,"text2");
var text2Col = findIndexCol(SHTvalues,"text2");
Logger.log(text2Col)
Logger.log(text2Row)
I can't understand why my logs return the correct values for text1Row and text1Col but when it is called a second time the text2Row and text2Col both return null
I believe your goal as follows.
You want to search a text value from a sheet in the Google Spreadsheet, and want to retrieve the row and column numbers of the found values.
You want to achieve this using TextFinder.
For this, how about this answer?
Sample script:
var findText = "text1";
var sheet = SpreadsheetApp.openById('the-gsheet-id');
var CurrSheet = sheet.getSheetByName('Sheet1');
var SHTvalues = CurrSheet.createTextFinder(findText).findAll();
var result = SHTvalues.map(r => ({row: r.getRow(), col: r.getColumn()}));
console.log(result)
Note:
About my logs return the correct values for text1Row and text1Col but when it is called a second time the text2Row and text2Col both return null in your script, if there are the values of text1 and text2 in Sheet1, text1Row, text1Col, text2Col and text2Row has the values. If only the value of text1 is put in Sheet1, text1Col and text2Col has the values. But text2Col and text2Row has no values (null). Please be careful this.
But in this case, when 2 values of `text1 are put to the cells "A1" and "A2", only "A2" is returned. Also please be careful this.
In this sample script, please enable V8.
References:
createTextFinder() in Class Sheet
Class TextFinder
Here's a script that I used for searching through my spreadsheets when I'm having trouble finding the sheet I want. It does read another sheet to get a list of spreadsheets to search through.
function regexSearch(sObj) {
var ass=SpreadsheetApp.getActive();
var startRow=2;
var msrsh=ass.getSheetByName('MultiSearchResults');
msrsh.clearContents();
msrsh.appendRow(['Path','FileName','FileId','SheetName','CellA1Notation','Value','Pattern']);
msrsh.activate();
var sh=ass.getSheetByName('SelectedSpreadsheets');
var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues()[0];
var getArrayIndex={};
hA.forEach(function(e,i){getArrayIndex[e]=i;});
var rg=sh.getRange(startRow,1,sh.getLastRow()-startRow+1,sh.getLastColumn());
var ssA=rg.getValues();
var matches='';
var n=0
for(var k=0;k<ssA.length;k++) {
var fileid=ssA[k][getArrayIndex['FileId']];
var filename=ssA[k][getArrayIndex['FileName']];
var filepath=getFilePathFromId(ssA[k][getArrayIndex['FileId']]);
//Logger.log(fileid);
var ss=SpreadsheetApp.openById(fileid);
Logger.log(sObj.pattern);
var tf=ss.createTextFinder(sObj.pattern).useRegularExpression(true);
var all=tf.findAll();
for(var i=0;i<all.length;i++) {
if(i==0)n++;
matches+=Utilities.formatString('<br /><b>Path:</b> %s <b>Sheet:</b> %s <b>Cell:</b> %s <b>Value:</b> %s<hr width="100%"/>',filepath,all[i].getSheet().getName(),all[i].getA1Notation(),all[i].getValue());
msrsh.appendRow([filepath,filename,fileid,all[i].getSheet().getName(),all[i].getA1Notation(),all[i].getValue(),sObj.pattern]);
}
}
if(matches) {
sObj.matches=matches;
sObj.message=Utilities.formatString('<p>Pattern %s was found in %s spreadsheet out of a total of %s</p>',sObj.pattern,n,ssA.length);
}else{
sObj.message=Utilities.formatString('No Matches found for %s',sObj.pattern);
}
return sObj;
}

How do I get an array name out of a javascript array? Possibly a syntax issue - Noob

I am creating a program in a which a video plays of a person speaking and chunks of the text appear in a div as the words are spoken with a translation. I am trying to write a javascript function to make that happen. Basically, I am changing the visibility of the div's with "setTimeout" so the text is revealed at the right time.
I have these 3 arrays
var invite =["itimes", "idivs"]; //names of 2 arrays which contain the info for the "invite" text block
var itimes =["0", "642", "950", "2555", "1113"]; //times in msec when text should be revealed
var idivs = ["speech_bubble", "i1", "i2", "i3", "i4"]; //divs to be revealed
These are the 2 functions I have written to cause the text to be revealed
function reveal(){ //change visibility of div name retrieved
var textchunk = "invite"
var divs = textchunk[1];
var div = {Value: divs[x]}; //x value comes from timedreveal div
var divtoreveal = document.getElementById(div);
divtoreveal.style.visibility = 'visible';
}
function timedreveal() {
var textchunk = "invite" //the textchunk value will later be set by another function but
//here I just set it to invite so I could try to get it working
var times = textchunk[0];
for(var x = 0; x < times.length; x++)
{
var wait = {Value: times[x]};
alert(JSON.stringify(wait, null, 4));
setTimeout(reveal, wait);
}
}
timedreveal retrieves 'itimes' just fine from the 'invite' array but then when I alert its length I get the length of the word 'itimes' and not the length of the 'itimes' array. The first value it retrieves is "i" not "0". It is not treating 'itimes' as the name of the array but as as the values of an array named 'times' with 6 elements. I have tried to look this up and read a bunch of posts but haven't understood how to fix it. One suggested I put all three arrays inside a sort of superarray but I don't understand how to access the data in that case. Any advice would be great.
Thanks, Kate
var itimes =["0", "642", "950", "2555", "1113"]; //times in msec when text should be revealed
var idivs = ["speech_bubble", "i1", "i2", "i3", "i4"]; //divs to be revealed
var invite =[itimes,idivs];
var times = invite[0]; // in timedreveal()
var divs = invite[1]; // in reveal()
can you try like this, because you're pushing strings in array not array themselves.
You are assigning a string instead of array.
var textchunk = "invite"
should be
var textchunk = invite;
In your case
> var textchunk = "invite"
> var divs = textchunk[1];
textchunk will a string "invite" and techchunk[1] will return the letter at position 1, so divs will have value n

storing local variable then re-running function?

So I'm making an app that, in a nut shell, takes dimensions from the user and spits out the surface area but it's quickly becoming really repetitive.
function calc() {
var dim1main = +document.getElementById("dim1main").value || 0;
var dim2main = +document.getElementById("dim2main").value || 0;
var mainSurA = dim1main * dim2main;
var dim1mainD1 = +document.getElementById("dim1mainD1").value || 0;
var dim2mainD1 = +document.getElementById("dim2mainD1").value || 0;
var mainD1SurA = dim1mainD1 * dim2mainD1;
// ...
var dim1mainD6 = ...
// ...
var totalSurA = mainSurA + mainD1SurA ... + mainD6SurA;
}
So the idea was to have hundreds of text inputs hidden until the user wanted them and everything that was left empty would run through as zero, therefor not messing with the total. I think I'm safe in assuming this is horrible javascript.
I've been looking for a way to run a function multiple times and store each local variable somewhere for later use. I've played with arrays by deleting the input values onClick but each time I run the function with .push it replaces the first value with the second. I've read about localStorage but I'm not sure that's what I'm looking for. Any suggestions? Sorry if this is too vague.
I have read about storing data in objects as well as global variables but I've heard that gets messy.
One way you can do this is instead of hiding many elements you can dynamically create new input elements when needed. You can give your elements a specific class which you can use to get it via a HTMLCollection and compute the total dimension.
For example:
document.getElementById('add').onclick = function()
{
var container = document.getElementById('container');
var subContainer = document.createElement("div");
var dim1 = document.createElement("input");
var dim2 = document.createElement("input");
dim1.className = "dim1";
dim2.className = "dim2";
dim1.value = dim2.value = 0;
subContainer.className = "sub-container";
subContainer.appendChild(dim1);
subContainer.appendChild(dim2);
container.appendChild(subContainer);
}
document.getElementById('calc').onclick = function()
{
var arrayDim1 = document.getElementsByClassName('dim1');
var arrayDim2 = document.getElementsByClassName('dim2');
var totalSurA = 0;
for (var i = 0; i < arrayDim1.length; i++) {
totalSurA += +arrayDim1[i].value * +arrayDim2[i].value;
}
console.log(totalSurA);
}
<div id="container"></div>
<button id="add">Add Dimension</button>
<button id="calc">Calculate</button>
For storing past page sessions you can use localStorage as you said. I would in JavaScript as a 2D array of each row item (or you can use an array of objects with a property for dim1/dim2), like so:
[
[dim1_0, dim2_0],
[dim1_1, dim2_1],
...
]
Although before saving it to local storage you need it in a text format, which you can convert it to using JSON.stringify()

JavaScript creating array with input name and values

I was formulating this question:
Is it possible to make an array automatically from the .name and .value data used in all the inputs type text?
This is the reference doing manually:
var foo = [];
foo['bar'] = 'foo data';
foo['foo'] = 'bar data';
I got this idea... And it works...
var foo[];
for (var i = 0; i < document.getElementsByTagName('input').length; i++)
{
foo[document.getElementsByTagName("input")[i].name] = document.getElementsByTagName("input")[i].value;
};
The mission was to make it work automatically.
Get the .name of the input and get the .value of that input.
I was editing the question to post it here... When I figured out how to make it. I decided to leave here the reference, it'll be useful for someone, I guess.
Feedback is welcome.
Your code is reasonable enough, except for two things:
Use an object instead of an array.
Create the list of inputs only once.
So you could do:
var values = {};
var inputs = document.getElementsByTagName('input');
for( var i = 0; i < inputs.length; i++ ) {
values[inputs[i].name] = inputs[i].value;
}

How to split a comma separated string from user input

I want to be able to have the user list things in an input box (comes up via an alert) and then once submitted have those options replace the default text in the string. They need to be separated after each comma as well and with each thing listed, the loop should paste the text into it when it runs, and repeat with the rest in the list.
Is this possible?
This is what I'm working on right now: http://jsbin.com/nivah/1 and it'll only allow you to type in one thing. Because if you type in several options with commas it includes the commas and all the options in the link which obviously won't return anything.
Here's my javascript code.
var link0='http://www.twitter.com/';
var user=['bob', 'joe', 'tony'];
var user = prompt("I want to message:", user);
var link3=".tumblr.com";
var iframe = document.getElementById("username");
var opt = (link0 + user + link3);
var el = document.createElement("iframe");
for(var i = 0; i < user.length; i++) {
el.setAttribute("src", opt);
iframe.appendChild(el);
}
var array = user.split(',');
Anyone know what I am doing wrong?
I had it working before to repeat the loop based on what i submitted but it was doing it by make each letter of the word its own link in the iframes. Which is not what I want, but as close as I've ever gotten to the loop interaction with the user inputted text.
You need to use the split() but at the right place in your code. Also, your logic is not going to work, You need to create each iframe within the for loop, something like this -
WORKING DEMO - http://jsbin.com/ciquvatu/1/edit
var link0='http://www.tumblr.com/ask_form/';
var user = ['killthemwithyourawesome', 'barrowman-ilove', 'down-with-these-ships'];
var user = prompt("I want to message:", user);
var link3=".tumblr.com";
var array = user.split(',');
for(var i = 0; i < array.length; i++) {
var iframe = document.getElementById("username");
var opt = (link0 + array[i] + link3);
var el = document.createElement("iframe");
el.setAttribute("src", opt);
iframe.appendChild(el);
}
This should do what you are looking for.

Categories

Resources