Write element multiple times - javascript

I'm writing a page to interact with multiple camera's at the same time. Because of that I have a page with basically 1 set of control's that call on a JavaScript that repeat an X number of time's where only the name and 1 variable changes. Is there a way to read the document and write it an X number of times and replace only those value's in each pass? I know how to do it in PHP but i would like to be able to do it client side.
So basically you have:
<div name="camera1" style="left:100px">
<input type="button" onclick="setFps(1)">
</div>
Where the 100px and the 1 need to be changed every pass.

<script>
for(var i = 0; i < 10; i++)
document.write('<div name="camera'+i+'" style="left:100px;"><input type="button" onclick="setFps(1)"></div>');
</script>
but, unless you have a good reason to do this, i would not recommend doing it like this.
it's just the easiest way to do it and given the fact that this is your only post and it is just 1 simple google-search away, this'll do.

I would do this:
---HTML---
<div id="cameraDisplay">
<script>displayCameras()</script>
</div>
---Javascript---
function displayCameras()
{
var parent = document.getElementById("cameraDisplay");
parent.innerHTML = ""; //Clear parent before adding cameras
var fpsValues = [1, 2, 3, ...]; //Array of all the FPS integers
var leftValues = [100, 200, 300, ...]; //Array of all the left stylings
for (var i = 0; i < numberOfCameras; i++)
{
var camera = document.createElement("div");
camera.setAttribute("name", "camera" + i.toString());
camera.style.left = leftValues[i].toString + "px";
var input = document.createElement("input");
input.type = "button";
(function() { //Create an anonymous function to store correct value of i - otherwise mutable errors occur
var fps = i;
input.onclick = function() {setFps(fpsValues[fps]);};
})();
camera.apendChild(input);
parent.appendChild(camera);
}
}

Related

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()

Get the value of multiple input texts with Actionscript 3

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.

Add numbers from dynamic site with new page load

How do you write a function/ listener in javascript that can fire when html updates?
html page is limited to the last 100 records
html page continuously adds new records (nodes)
I need to...
push the values into an array or increment a variable to sum the values
display the running total in html
Trying to create a counter that adds new values to the sum.
I believe the code below only executes once.
window.onload = function() {
var data = document.getElementsByTagName('span');
var len = data.length;
var total = 0;
var searchValue = "value";
for (var i = 0; i < len; ++i) {
var styles = data[i].getAttribute('style');
if (styles == searchValue) {
var txt = data[i].innerHTML;
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);
};
Yes you can do this with just JavaScript, and a little HTML/CSS for displaying the number.
Note that it requires a fair deal of experience to manage an addon with cross-origin requests, and to show it to the user.

Binding an input element to a JavaScript object

I want to introduce a simple notation to bind a HTML <input> element to a JavaScript object. Something like:
<script>
var qform = {
uid : "",
pass : ""
};
</script>
<form method="get" action="#">
<input id="temp0" type="text" name="uid" bind="qform.uid" />
<input id="temp1" type="password" name="pass" bind="qform.pass" />
<input type="submit" value="submit" />
</form>
So that any changes to the <input>s will change my JS variable. The way I'm trying to implement it is:
<script>
var x = 0;
for(x = 0; x < 2; x++) {
var inputField = document.getElementById("temp" + x);
var bindObj = inputField.getAttribute("bind");
var bindObjTree = bindObj.split(".");
var parent = window;
for (var i = 0; i < bindObjTree.length - 1; i++) {
parent = parent[bindObjTree[i]];
}
child = bindObjTree[bindObjTree.length - 1];
inputField.value = parent[child];
inputField.onchange = function() {
var xp = parent;
var xc = child;
xp[xc] = inputField.value;
alert(JSON.stringify(window["qform"]));
};
} // for
</script>
However only the second input field behaves the way I want to. Can someone explain why that is? I'm guessing it has something to do with closures. I'm really trying to understand what I'm doing wrong rather than find a solution (I can easily work around this with JQuery, but I don't really want that).
The issue is with these:
parent = parent[bindObjTree[i]];
child = bindObjTree[bindObjTree.length - 1];
and
inputField.onchange = function() {
var xp = parent; // Always refers to the element retrieved at index 1 of the for loop
var xc = child; // Always refers to the element retrieved at index 1 of the for loop
// This is regardless of which input's event handler executes
xp[xc] = inputField.value;
alert(JSON.stringify(window["qform"]));
};
These will always refer to the elements found in the last iteration of the for loop because of closure.
inputFields needs to be an an array so it doesn't get overwritten in the loop or
you can place an id in the form tag and instead reference it to get the fields as its child elements.
Your child variable is global. Try to use:
var child = bindObjTree[bindObjTree.length - 1];
instead. Since it is global, you will overwrite the global child variable on the second turn.

Adding names to an array and outputting them to a table

I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length

Categories

Resources