nested for loop breaks parent loop - javascript

function next() {
document.getElementById('config').setAttribute("hidden","true");
document.getElementById('formdiv').removeAttribute("hidden");
mixer();
}
function mixer() {
var x = 0;
for (var i = 0; i < parseInt(document.getElementById('nm').value); i++) {
var title = document.createElement("P");
title.style = "font-family:verdana;font-size:18px;";
title.id = "p"+String(i);
document.getElementById("myForm").appendChild(title);
document.getElementById("p"+String(i)).innerText = "Enter the amount of mixer number "+String(i+1);
var mixers = document.createElement("INPUT");
mixers.type = "text";
mixers.id = "m"+String(i);
mixers.size = '1';
document.getElementById("myForm").appendChild(mixers);
var options = ['Select a unit','ml','L','UK Pints','US Pints'];
var dropdown = document.createElement("SELECT");
dropdown.id = "s"+String(x);
document.getElementById("myForm").appendChild(dropdown);
/*for (j = 0; i < options.length; j++) {
var optiontag = document.createElement("OPTION");
optiontag.value = options[j];
optiontag.innerText = options[j];
document.getElementById("s"+String(x)).appendChild(optiontag);
}*/
x += 1;
}
}
this function creates the output when passed mn = 3
https://imgur.com/Hhv6fVE
when i un-comment the nested loop at the bottom, it outputs this
https://imgur.com/80juxgX
it should output the same as the first image but with the options for the
dropdown menus

Related

Having issues creating a for loop for a list created in JS

I'm trying to for loop the H1 object through a list 10 times. I'm not sure where I went wrong any help would be appreciated.
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
var helloWorld = document.getElementById("OLJS");
for (var i = 0; headOne < 10; i++){
var listItems = document.createElement("li");
listItems.innerHTML = headOne[i];
helloWorld.append(listItems);
}
If you want to loop 10 times then do:
for (let i = 0; i < 10; i++) {
// Do something
}
And in your case if you are trying to access each letter of headOne element and append it to the helloWorld list then you can do the following:
for (let i = 0; i < headOne.textContent.length; i++) {
let listItems = document.createElement('li')
listItems.textContent = headOne.textContent[i]
helloWorld.append(listItems)
}
You might also want to read more about Loops and iteration
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
//var helloWorld = document.getElementById("OLJS");
for (var i = 0; i < 10; i++) {
var listItems = document.createElement("li");
listItems.innerHTML = "order list item " + (i + 1);
newOrderedList.append(listItems);
}

.innerHTML edits HTML but doesnt display

so I have a bit of code that generates a few spans for display of a few range inputs but when the span is edited it shows as if it were edited in the console but not the page
for (var i = 0; i < 5; i++) {
text = document.createElement('span')
span[pos][i] = text;
console.log(text)
div.innerHTML += list[i]
text.setAttribute("id",`${pos}0${i}`)
div.appendChild(text);
div.appendChild(space);
}
div.appendChild(document.createElement('p'))
for (var i = 0; i < 5; i++) {
space = document.createElement('span')
space.setAttribute("style","padding-left: 40px")
slider = document.createElement('input')
range[pos][i] = slider;
slider.setAttribute("type","range")
slider.setAttribute("id",`${pos}1${i}`)
div.appendChild(slider);
div.appendChild(space);
console.log(div, i)
}
for (var i = range.length - 1; i >= 0; i--) {
for (var j=0; j<5; j++) {
span[i][j].innerHTML = range[i][j].value;
//console.log(j)
}
}
I don't understand what you are going to do with the 5 sliders?
var range = [];
var span = [];
function init() {
var div = document.createElement('div');
for (var i = 0; i < 5; i++) {
var text = document.createElement('span');
span[i] = text;
console.log(text);
//div.innerHTML += list[i]
text.setAttribute("id",`txt0${i}`);
div.appendChild(text);
var space = document.createElement('span');
div.appendChild(space);
}
div.appendChild(document.createElement('p'))
for (var i = 0; i < 5; i++) {
var space = document.createElement('span');
space.setAttribute("style","padding-left: 40px");
var slider = document.createElement('input');
range[i] = slider;
slider.setAttribute("type","range");
slider.setAttribute("id",`slider1${i}`);
div.appendChild(slider);
div.appendChild(space);
console.log(div, i)
}
for (var i = range.length - 1; i >= 0; i--) {
for (var j=0; j<5; j++) {
span[i].innerHTML = range[i].value;
//console.log(j);
}
}
document.body.appendChild(div);
}
<body onload="init()">
</body>

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>

Can I do For loop on Google Script?

I was trying to put some information of my sheet in a array, to use in a graphic later. But this error keeps showing :(
Error: Syntax error (line 8, archive "Código")
function onOpen() {
var proposta = SpreadsheetApp.getActive().getSheetByName('Proposta de solução');
var ids = proposta.getRange('A10:A26');
var names = proposta.getRange('B10:B26');
var esforcos = proposta.getRange('F10:F26');
var name = [
for (var i = 0; i < 17; i++) {
names.getCell(i, 1).getValue();
}
]
var id = [
for(var j = 0; j < 17; j++) {
ids.getCell(j,1).getValue();
}
]
var esforco = [
for(var k = 0; k < 17; k++) {
esforcos.getCell(k,1).getValue();
}
]
}
This should get the results you want:
function onOpen() {
var proposta = SpreadsheetApp.getActive().getSheetByName('Proposta de solução');
var ids = proposta.getRange('A10:A26');
var names = proposta.getRange('B10:B26');
var esforcos = proposta.getRange('F10:F26');
var name = [];
var id = [];
var esforco = [];
for (var i = 0; i < 17; i++) {
name.push(names.getCell(i, 1).getValue());
id.push(ids.getCell(i, 1).getValue());
esforco.push(esforcos.getCell(i, 1).getValue());
}
}

Why won't the addEventListener trigger on change?

Trying to get the eventlistener to run, i.e. when I select United Kingdom, another selection box will appear to select county (county() function), but for some reason the addEventListener will not call the function, and I can't fathom how to pass the selected country to the county function? Any ideas please.
function countries() {
xmlRequest("countries.xml");
var country_selector = document.createElement("SELECT");
country_selector.id = "cou n tryselection";
document.getElementById("quiz").appendChild(country_selector);
var t = document.getElementById("countryselection");
var c_opt = document.createElement("option");
c_opt.text = "Please select";
c_opt.selected = true;
t.add(c_opt);
c_opt = document.createElement("option");
c_opt.text = "United Kingdom";
c_opt.value = "1";
t.add(c_opt);
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
var x = xmlDoc.getElementsByTagName("country");
for (i = 0; i < x.length; i++) {
var opt = document.createElement("option");
opt.text = x[i].getElementsByTagName("country_name ")[0].childNodes[0].nodeValue;
t.add(opt);
}
}
function county(Country) {
if (!document.getElementById("countyselection")) {
if (Country === "1") {
xmlRequest("counties.xml");
document.getElementById("quiz").innerHTML += "<select id='countyselection'></select>";
var t = document.getElementById("countyselection");
var y = xmlDoc.getElementsByTagName("county");
for (j = 0; j < y.length; j++)
{
var opt = document.createElement("option");
var txt = y[j].getElementsByTagName("county_name")[0].childNodes[0].nodeValue;
opt.text = txt;
t.add(opt);
}
}
} else {
var f = document.getElementById("countyselection");
document.getElementById("countyselection").parentNode.removeChild(f);
}
}
Because you're calling the function, not referencing it, and you have a space in the function name.
change
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
to
document.getElementById("countryselection").addEventListener("change", function() {
county(this.value);
}, false);
Also note that things like this
country_selector.id = "cou n tryselection";
is completely invalid, you can't use random text with spaces as an ID

Categories

Resources