Javascript - accessing array in an array - javascript

So I have this code:
function make_buttons (id) {
var operators = [["*","multiply"],["/","divide"],["+","add"],["-","divide"],["=","calc_it"]]
var parent = document.getElementById(id);
var input = document.createElement("input");
input.type = 'text'; input.id = 'inp';
parent.appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.innerHTML = i;
btn.id = i;
parent.appendChild(btn);
(function(index) {btn.onclick = function() {input.value += index;}})(i);
}
for (var j = 0; j < operators.length; j++) {
var operators[j][1] = document.createElement ("button");
};
So I have an array wich has array inside of it. Now I want to set the name of the variable to be operator name inside of the array. In current case it should be 'multiply'.
But it gives me a syntax error when doing this.
What I want to achieve is this :
var multiply = document.createElement ("button");
multiply.innerHTML = "*";
multiply.id = "*";
parent.appendChild(multiply);
multiply.onclick = function () {input.value += '*';};
var divide = document.createElement ("button");
divide.innerHTML = "/";
divide.id = "/";
parent.appendChild(divide);
var add = document.createElement ("button");
add.innerHTML = "+";
add.id = "+";
parent.appendChild(add);
var substract = document.createElement ("button");
substract.innerHTML = "-";
substract.id = "-";
parent.appendChild(substract);
But with the array, so that there is less code written and also less repetitiveness.

Related

How to use for loop to sum a numbers inserted by the user?

i'm trying to create a simple project where the user is prompted to enter how many numbers he would like to add(sum). then when he click the button, a javascript will create a number of input tags equal to the number he inserted and then he will fill them with a number and click another button to calculate the result of the summation and here is the problem. below is a simplified snippet explain what is the problem:
function CL(){
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type","text");
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
}
function Add(){
const y = 0;
const sum = 0;
var is;
for (var i = 1; i < 3; i++) {
is = i.toString();
y = Number(document.getElementById('y'+ is).value);
sum = sum + y;
}
document.getElementById("demo").innerHTML = sum;
}
in the for loop how can i use getElementById with variables id like item1,item2,item3,...,itemN??
is there other way to achieve what i want?
You can take all items with ID "y" + consecutive number prefix on this way document.getElementById('y' + i).value;
Do not use "Add" for function name and Functions do not have to start with capital letters!
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var res = 0;
for (var i = 1; i < 3; i++) {
res = res + +document.getElementById('y' + i).value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
A better way is ...
When you create elements, you can assign them a CLASS attribute that is one for all input elements. You can then take the values from all elements with this class.
Example:
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
// inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
inpt.setAttribute("class", "numbers"); //<-- Set class
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var list = document.getElementsByClassName('numbers'); //<-- Get by class
var res = 0;
for (var i = 0; i < list.length; i++) {
res = res + +list[i].value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
You can use ...args to collect arguments and use .reduce to add the arguments together.
const items = document.getElementById("items");
for (var i = 0; i < 3; i++) {
var inpt = document.createElement("input");
inpt.setAttribute("type","number"); //replaced with number
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
var newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline); //added newline appending
}
function sum(...args) {
return args.reduce((a, b) => a+b); //reduce arguments
}
<div id="items"></div><br /><button onclick="document.getElementById('answer').textContent = 'answer: ' + sum(+y0.value, +y1.value, +y2.value)">Add</button><div id="answer"></div>

Create div Using Array

I have an array of strings, I want to show each array element in its own <div> tag like
<div "class">one</div><div class"two">one</div> and each div tag should have a class that is common for all. All process start on click button
BUTTON CODE
<asp:Button OnClientClick="abc();" runat="server" />
JAVASCRIPT FUNCTION
function abc()
{
debugger;
var arrayVariable = "one,two,three";
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
}
You need to convert string into array first.
Use this:
function abc()
{
debugger;
var stringVariable = "one,two,three"; // string
var arrayVariable = stringVariable.split(","); // now string to array
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
return false;
}
Use This
<asp:Button OnClientClick=" javascript:return abc();" runat="server" />
<script>
function abc() {
debugger;
var stringVariable = "one,two,three"; // string
var arrayVariable = stringVariable.split(","); // now string to array
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
return false;
}
</script>
Try it with less number variable and pure javascript, because you only used single line jQuery code $('#inputcomshow').append(temp);.
function abc(){
var arrayVariable = "one,two,three";
arrayVariable = arrayVariable.split(',');
for (i = 0; i < arrayVariable.length; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
document.getElementById("inputcomshow").appendChild(temp);
}
}

JavaScript: How Can I Make A Var "Array" Work?

Is there a way to name a var using a sort of "Array?" My code is this:
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
var Square[i] = document.createElement("div");
Square[i].style.position = "relative";
Square[i].style.float = "left";
Square[i].style.width = "50px";
Square[i].style.height = "50px";
Square[i].id = "square" + (i + 1);
for(var ii = 0; ii < 6; ii++){
var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
getTestColor += TestColor;
}
Square[i].style.backgroundColor = "#" + getTestColor;
SquareCont.appendChild(Square[i]);
}
I know my code doesn't work, but I want to implement the same idea so I can get a result of this:
var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc
I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?
var Square = {};
var SquareCont = document.createElement('div');
var getHorizontalSquares = 10;
var getVerticalSquares = 10;
var TestColorArray = ['a','b','c','f','e','0','1','2','3','3','4','5'];
var getTestColor = '';
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
Square['Square'+i] = document.createElement("div");
Square['Square'+i].style.position = "relative";
Square['Square'+i].style.float = "left";
Square['Square'+i].style.width = "50px";
Square['Square'+i].style.height = "50px";
Square['Square'+i].id = "square" + (i + 1);
for(var ii = 0; ii < 6; ii++){
var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
getTestColor += TestColor;
}
Square['Square'+i].style.backgroundColor = "#" + getTestColor;
SquareCont.appendChild(Square['Square'+i]);
getTestColor = '';
}
console.log(Square);
This example does what you want using an object instead of an array, but meets your desire to dynamically create accessible Square1, Square2, etc... They are all contained in Square. In the console with this snippet, you will see that 100 squares are created and added to the Square object. They will be accessible by Square.SquareX (where X is some number), or Square['SquareX'], or Square['Square'+X] where X is some number again.
Your declaration syntax is not valid. But, I think the larger point you are trying to get to is to be able to populate an array with dynamically created elements and that you can do:
var squares = []; // Array must exist before you can populate it
var testColorArray = ["green", "yellow", "blue", "orange", "silver"];
var getTestColor = null;
function makeSquares(count){
for(var i = 0; i < count; i++){
// Just create the element and configure it. No need to worry about the array yet
var element = document.createElement("div");
element.style.float = "left";
element.style.width = "75px";
element.style.height = "75px";
element.id = "square" + (i + 1);
element.style.backgroundColor = testColorArray[Math.floor(Math.random()* testColorArray.length)];
element.textContent = element.id;
squareCont.appendChild(element);
// Now, add the element to the arrray
squares.push(element);
}
// Test:
console.log(squares);
}
makeSquares(10);
<div id="squareCont"></div>

Converting if...else statement into for-loop

I have one generous piece of code with several if...else statements and I would need to convert this into a loop. The problem is, each time it makes a loop, there must be some different id to the function so it works properly.
Let's take a look at the code:
// Count how many inputs there are in element with id "tempResult"
var inputCount = document.getElementById('tempResult').getElementsByTagName('input').length;
if (inputCount == 1) // if there is 1 input, generate 1 line
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
}
else if (inputCount == 2) // if there are 2 inputs, generate 2 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
}
else if (inputCount == 3) // if there are 3 inputs, generate 3 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
var str = document.getElementById('tempString3').value;
var arrayOfStrings3 = str.split('*');
for(var i = 0; i < arrayOfStrings3.length; i++)
{
var div3 = document.getElementById('div3');
var mi3 = document.createElement('input');
mi3.setAttribute('type', 'text');
mi3.setAttribute('size', '5');
mi3.setAttribute('id', 'string3' + (i+1));
mi3.setAttribute('value', arrayOfStrings3[i]);
div3.appendChild(mi3);
}
}
else if (inputCount == 4) // if there are 4 inputs, generate 4 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
var str = document.getElementById('tempString3').value;
var arrayOfStrings3 = str.split('*');
for(var i = 0; i < arrayOfStrings3.length; i++)
{
var div3 = document.getElementById('div3');
var mi3 = document.createElement('input');
mi3.setAttribute('type', 'text');
mi3.setAttribute('size', '5');
mi3.setAttribute('id', 'string3' + (i+1));
mi3.setAttribute('value', arrayOfStrings3[i]);
div3.appendChild(mi3);
}
var str = document.getElementById('tempString4').value;
var arrayOfStrings4 = str.split('*');
for(var i = 0; i < arrayOfStrings4.length; i++)
{
var div4 = document.getElementById('div4');
var mi4 = document.createElement('input');
mi4.setAttribute('type', 'text');
mi4.setAttribute('size', '5');
mi4.setAttribute('id', 'string4' + (i+1));
mi4.setAttribute('value', arrayOfStrings4[i]);
div4.appendChild(mi4);
}
}
As you can see, we repeat a certain amount of time the same function depending on how much inputs we have in the div tempResult:
var str = document.getElementById('tempStringX').value;
var arrayOfStringsX = str.split('*');
for(var i = 0; i < arrayOfStringsX.length; i++)
{
var divX = document.getElementById('divX');
var miX = document.createElement('input');
miX.setAttribute('type', 'text');
miX.setAttribute('size', '5');
miX.setAttribute('id', 'stringX' + (i+1));
miX.setAttribute('value', arrayOfStringsX[i]);
divX.appendChild(miX);
}
The X, replaced by numbers each time, are important, the function will not properly work without it (except for the divX, I could generate the inputs inside the same div, but whatever). The above code is working perfectly.
What I'm trying to do, is to use a for() instead of if...else(), so that I don't need to manually edit the code each time we add a new div. I'm not very familiar with for() and my tries with the already existing ones in my code as models were not successful.
Here's how the HTML looks like:
<div id="tempResult">
<input type="text" id="tempString1" value="valueTempString1" />
<input type="text" id="tempString2" value="valueTempString2" />
<input type="text" id="tempString3" value="valueTempString3" />
<input type="text" id="tempString4" value="valueTempString4" />
</div>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
And if you wonder what this whole code is doing, explanation's here. Thanks :)
The if loops in the code you posted would be used as a for loop. i.e, you would be iterating the same times the input count would be. So you can condense the same code into this.
var inputCount = document.getElementById('tempResult')
.getElementsByTagName('input').length;
// First loop that iterates over the input count
for (var j = 1; j <= inputCount; j++) {
var str = document.getElementById('tempString' + j).value,
arrayOfStrings = str.split('*');
// Second loop would iterate over the strings that would be split
for (var i = 0; i < arrayOfStrings.length; i++) {
var div = document.getElementById('div' + j);
var mi = document.createElement('input');
mi.setAttribute('type', 'text');
mi.setAttribute('size', '5');
mi.setAttribute('id', 'string' + j + '-' + (i + 1));
mi.setAttribute('value', arrayOfStrings[i]);
div.appendChild(mi);
}
}
Why do you want the variable to have the number of the item? You could run all code inside the for statement and the variable name doesn't have to change.
thisdiv = document.getElementById('div'+i);
thisdiv....all changes to thisdiv go here

createElement (input) with Id ;with counter ,Id1,Id2,Id3

i trie to generate dynamic Input fields with unique Ids but i stucked:
function addTxtBx(){
var txtBxHolder = document.getElementById('txtBoxHolder');
var newTxtBx = document.createElement('input');
newTxtBx.type = 'text';
var i=1;
//newTxtBx.id = document.getElementById("txtWaypoint"[i])
if(i<10){
newTxtBx.id = "txtWaypoint"+[i];
i++;
break;
}
txtBoxHolder.appendChild(newTxtBx);
}
i tried it with a for() but always got Id='name'9,
i know im an trainee. :)
I think so where you miss to loop it properly.
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input');
text.type = "text";
text.id = "txtWaypoint" + i; //id created dynamically
document.getElementById('divsection').appendChild(text);
}
}
Try it

Categories

Resources