Javascript: Dynamically Creating Variables for Loops

JavaScript: Dynamically Creating Variables for Loops

You should use an array:

function createVariables(){
var accounts = [];

for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}

return accounts;
}

You then have access to accounts[0] through accounts[20].

How do I create dynamic variable names inside a loop?

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}

How to dynamically create variable with loop?

You need to give the emails a name to submit them

Also I removed the onsubmit form the submit button. It does not belong there and can be removed. You have a submit event handler and that should do it

const container = document.getElementById("container");
document.getElementById("nameForm").addEventListener("submit", tableGen);
document.getElementById("okButton").addEventListener("click", emailGen);

//fuction to genrate email field
function emailGen() {
const quant = document.getElementById("quantity").value;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (let i = 0; i < quant; i++) {
var emailGen = document.createElement("input");
emailGen.type = "email";
emailGen.id = "email" + i;
emailGen.name = "email" + i;
emailGen.placeholder = "Member's Email";
container.appendChild(emailGen);
}
}

//function for table generator
function tableGen(e) {
e.preventDefault();
const body = document.querySelector("body");
const table = document.createElement("table");
const tblbody = document.createElement("tbody");
const input1 = document.getElementById("input1").value;
const quan = document.getElementById("quantity").value;

const emails = container.querySelectorAll("[type=email]")

console.log(emails.length)

//table rows loop
for (let i = 0; i < quan; i++) {
const tblrow = document.createElement("tr");
for (let j = 0; j < emails.length; j++) {
const tblcell = document.createElement("td");
//table column loop
const pname = document.createTextNode(input1);
tblcell.appendChild(pname);
const tname = document.createTextNode(emails[j].value);
tblcell.appendChild(tname);
tblrow.appendChild(tblcell);
}

tblbody.appendChild(tblrow);

}
console.log
table.appendChild(tblbody);
body.appendChild(table);
table.setAttribute("border", "4");
}
<form id="nameForm">
<input type="text" id="input1" placeholder="Name"><br/>
<input type="number" id="quantity" name="quantity" placeholder="Total Members(max 10)" min="1" max="10">
<button type="button" id="okButton">OK</button>
<div id="container"></div>
<br/>
<input type="submit" value="submit">
</form>

Dynamic variable in loop javascript

You don't want to create 9 variables. Trust me. You want to create an object.

var m = {};
for(var i=1; i<10; i++){
m[i] = "Something";
}

You can also create an array (m = []), but since you are starting at 1 and not 0, I'd suggest an object.

Dynamically create variables based on HTML inputs made into dynamically added form fields, then use them in a for loop string

Bergi's comment helped me enough for what I had. I will not be checking this today so I thought I should mark it answered for now. What I had was fine, I just had to assign colorNum to an array. As for putting this in my string, I'll have to play around a bit another day - doesn't need to be in a loaded question.

Edit: Unless someone has an idea for the string? I am going to try and figure out how to list each item in the array in the string separated by text without creating dozens of new variables for each input.

Edit 2: I figured out how I will do the part above. After I do have the array, I just have to convert to a string and then split/insert/other string work from there.

var colorNumX = [];
for (i = 0; i <= count - 1; i++) {
colorNumX[i] = document.getElementById("field" + i).value;
}

var colorString = colorNum.toString();

Create dynamic variable names and values using for loop: JavaScript

Anytime you're struggling to dynamically define variable names it's an indication that you should step back and reconsider your data structures. It's almost always the wrong choice that leads to difficult, messy code.

In this case it looks like you have three things that have an id and a temp, humidity and time property. This is exactly what objects are for.

For example you might represent the data like:

let data = { machine_41: {temp: 40, humid: 10, time: 200},
machine_44: {temp: 30, humid: 15, time: 500},
} // etc

Now all your data is in one place and you can access it with simple properties:

 data.machine_41.temp 

To go from your array of numbers to this object is simple with reduce():

var activeMachines = [41,44,46]
let data = activeMachines.reduce((obj, machineID) => { // some fake data temp = 20 // or document.getElementById etc.. humidity = 10 time = 600 obj['machine_'+machineID] = {temp, humidity, time} return obj}, {})console.log("machine_41 humidity:",data.machine_41.humidity)console.log(data)

Dynamic variable name in loop

Use an array:

var marker = [];

for (i=0; i < location.length; i++) {
marker[counter] = new google.maps.Marker({

javaScript - How to assign multiple dynamic values to a variables into the loop

Hey @Peter Krebs thanks for your efforts, but the solution that i need is:

        let opponentsA = [];
let opponentsB = [];

for (var i = 0; i < otp.length; i++) {
opponentsA[i] = otp[i].split(" - ")[0];
opponentsB[i] = otp[i].split(" - ")[1];

}

console.log(opponentsA[0]); //access the 1st opponent dynamically
console.log(opponentsA[20]); //access the 20h opponent dynamically

Dynamically creating variables in a forEach loop - Javascript

If I understand your question correctly you're attempting to store all of the names for later usage. If so you could probably go for something like:

var names = [];
data.forEach(function(d) {
names.push(d.Name);
});

Or simply:

var names = data.map(d => d.Name);


Related Topics



Leave a reply



Submit