repeat appendChild x times - javascript

I have this simple code wrapped inside a function:
slots = timeset / 2;
var oneslot = document.createElement("option");
document.getElementById('presentingslots').appendChild('oneslot');
the variable slots changes obviously. I want to appendChild oneslot x times where x = slots
How would I go about this?

If slots is small, you can get away with appending each element in a loop:
slots = timeset / 2;
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
document.getElementById('presentingslots').appendChild(oneslot);
}
If slots can be large, then you'll want use a DocumentFragment:
slots = timeset / 2;
var df = document.createDocumentFragment();
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
df.appendChild(oneslot);
}
document.getElementById('presentingslots').appendChild(df);
This will be more efficient since the DOM is only updated once.

Try this:
slots = timeset / 2;
for (var i = 0; i < slots; i += 1) {
var oneslot = document.createElement("option");
document.getElementById('presentingslots').appendChild('oneslot');
}

You can use a loop (for, while) to do this.
slots = timeset / 2;
var presentingslots = document.getElementById('presentingslots');
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
presentingslots.appendChild(oneslot);
}

A simple for loop would do the trick. And you can set the value as well as the text that is shown.
var slots = timeset / 2,
el = document.getElementById('presentingslots');
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
oneslot.text = i;
oneslot.value = 'set my value if you want';
el.appendChild(oneslot);
}
I made a simple jsFiddle to show.

Related

Setting multiple items in array to disabled with JavaScript

The current process of setting multiple inputs to disabled works for me, but seems to be way too much code due to the multiple for loops:
var textEditors = document.getElementsByClassName('textEditor'),
textareas = document.getElementsByTagName('textarea'),
radioInputs = document.getElementsByClassName('radioSelect'),
textInputs = document.getElementsByTagName('input');
for (var i = 0; i < textEditors.length; i++) {
textEditors[i].disabled = true;
}
for (var g = 0; g < textInputs.length; g++) {
textInputs[g].disabled = true;
}
for (var f = 0; f < textareas.length; f++) {
textareas[f].disabled = true;
}
for (var z = 0; z < radioInputs.length; z++) {
radioInputs[z].disabled = true;
}
But this above works fine for me. The below is what I would assume would work instead - put all elements into a single array, and iterate over a single array to set each to disabled. When I view the HTMLCollection via console.log it says disabled:true yet the element on the screen is not disabled. What am I missing here?
var textEditors = document.getElementsByClassName('textEditor'),
textareas = document.getElementsByTagName('textarea'),
radioInputs = document.getElementsByClassName('radioSelect'),
textInputs = document.getElementsByTagName('input');
var normalInputs = [];
normalInputs.push(textEditors);
normalInputs.push(textInputs);
normalInputs.push(radioInputs);
normalInputs.push(textareas);
for (var i = 0; i < normalInputs.length; i++) {
console.log(normalInputs[i])
normalInputs[i].disabled = true;
}
This will serve your purpose.
In your second method you're pushing the array capture from getElement into normalInputs array and than looping through that array and applying disable property on elements of inputArray which is eventually array of all the selected elements not individual element.
var textEditors = document.getElementsByClassName('textEditor'),
textareas = document.getElementsByTagName('textarea'),
radioInputs = document.getElementsByClassName('radioSelect'),
textInputs = document.getElementsByTagName('input');
var normalInputs = [];
normalInputs.push(textEditors);
normalInputs.push(textInputs);
normalInputs.push(radioInputs);
normalInputs.push(textareas);
normalInputs.forEach(e=>{
e.forEach(ele =>{
ele.disabled = true;
})
})
Without ES6
for (var i = 0; i < normalInputs.length; i++) {
for(let j=0; j< normalInputs[i].length; j++){
normalInputs[i][j].disabled = true;
}
}
A better approach is use concat
var normalInputs = [];
normalInputs = normalInputs.concat(textEditors,textInputs,radioInputs, textareas);
for(let i=0; i<normalInputs.length; i++){
normalInputs[i].disabled = true;
}
Well, give all of them same class like .inputs and get all of them with one expression:
var items = document.querySelectorAll( '.inputs' );
if it's not possible, get all of them like this:
var items = document.querySelectorAll( 'input, .textEditor, .radioSelect, textarea' );
then you can fix that with one loop for all of them:
for ( var i = 0; i < items.length; i++ )
items[ i ].disabled = true;

How to add diferent text for each element in DOM

Can someone tell me what is wrong with this code. I want to add a number from 0 to 4, but it added only the last number from my loop.
Thank you very much in advance.
<script>
for (i = 0; i < 5; i++) {
var createEl = i;
var createEl = document.createElement("li");
for (j = 0; j < 5; j++) {
createEl.innerHTML = [j];
}
console.log(createEl);
//<li>4</li>
//<li>4</li>
//<li>4</li>
//<li>4</li>
//<li>4</li>
}
You dont need the nested for loop just use the i value from the first loop
for (i = 0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
console.log(createEl);
}
This will only print the tags to console. In case you want to put them in another tag use it like this:
var node = document.createElement("div");
for (i = 0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
node.appendChild(createEl);
}
You don't need two loops for that.
var ulContainer = document.createElement("ul");
for (i=0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
ulContainer.appendChild(createEl);
}

For loop through array.length only executes once

The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i = 0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i = 0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i = 1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i = 0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i] * 2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i = 0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum % 10 == 0) {
console.log('Yes');
} else console.log('No');
}
In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
var current = numbers[j];
/...
}
JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)

How to I run a function for each piece of an array within a for loop in Javascript?

I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop

Create multidimensional array in for loop

I want to create a multidimensional array like this:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
array[.][....]
How can I do this in Javascript?
I have tried this:
var squares = new Array();
for(var i = 1; i <= 8; i++)
{
for(var j = 1; j <= 20; j++)
{
squares.push(i, j);
}
}
How can I accomplish this?
You can do something like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}
Output comes like:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
var array = []; // Main array
var numArrays = 10, // Number of sub-arrays
numPerArray = 20; // Number of squares per sub-array
for(var i = 0; i < numArrays; i++){
var subArray = [];
// Number to start at
var start = i * numPerArray;
// Count up to start + numPerArray
for(var j = start; j < start + numPerArray; j++){
subArray.push(j);
}
// Add to main array
array.push(subArray);
}
Use modulus operand to limit the inner array's size
var limit = 80
var inner_limit = 20
var square=[]
var inner =[]
for(var i=1;i<=limit;i++){
inner.push(i)
if(i%inner_limit==0){
square.push(inner)
inner = []
}
}
You can do it with two "for" loops. In the first loop you go through the main array and for each element add the elements from the second loop.
var arrayLength = 10; // Main array length
var limit = 20; // Number of squares
var array = [];
for ( var i = 0; i < arrayLength; i++ )
{
array[i] = []; // Create subArray
for( var j = 1; j <= limit; j++ )
{
array[i].push(j);
}
}

Categories

Resources