For loop through Array only shows last value - javascript

I'm trying to loop through an Array which then uses innerHTML to create a new element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
I have a UL with the id 'list' in my HTML.

Change your for loop:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
Use += instead of =. Other than that, your code looks fine.

I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.
function displayCountries(countries) {
const countriesDiv = document.getElementById('countriesDiv');
countries.forEach(country => {
console.log(country.borders);
const div = document.createElement('div');
div.classList.add('countryStyle');
div.innerHTML = `
<h1> Name : ${country.name.official} </h1>
<h2> Capital : ${country.capital} </h2>
<h3> Borders : ${country.borders} </h3>
<img src="${country.flags.png}">
`;
countriesDiv.appendChild(div);
});
}

Related

Why does this for loop only print one element?

Could you help me with this problem I found on MDN?
var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;
list.innerHTML = '';
totalBox.textContent = '';
var products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'
];
for (var i = 0; i < products.length; i++) {
var subArray = products[i].split(':');
var name = subArray[0];
var price = Number(subArray[1]);
total += price;
itemText = name + ' — $' + price;
var listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
totalBox.textContent = 'Total: $' + total.toFixed(2);
<div class="output">
<ul></ul>
<p></p>
</div>
I understand the logic but when I write only this part of the code below on my console, it returns only "Socks:5.99":
var products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'
];
for (var i = 0; i < products.length; i++) {
var subArray = products[i].split(':');
var name = subArray[0];
var price = Number(subArray[1]);
}
And the subArray contains only that element. It seems like the for loop doesn’t work. Shouldn’t it give me an entire new Array with:
Underpants — $6.99
Socks — $5.99
T-shirt — $14.99
Trousers — $31.99
Shoes — $23.99
Your code works, you just have to store each iteration result somewhere, like in a new array. Here is an example:
var products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'
];
var formattedProducts = [];
for (var i = 0; i < products.length; i++) {
var subArray = products[i].split(':');
var name = subArray[0];
var price = Number(subArray[1]);
formattedProducts.push(name + ' - $' + price);
}
console.log(formattedProducts);
Edit
In your first code example, the result was stored directly in your DOM, inside the .output ul list element:
var listItem = document.createElement('li');
listItem.textContent = itemText;
// list is defined outside the loop and will receive a new li element with the result of the iteration as textContent
list.appendChild(listItem);

How to give unique ids to each child div created dynamically?

The function displays eight elements on click in dynamically created divs using the slice() method. How can I give a unique id to each div? Your suggestions would be of great help to me.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++) {
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
}
I have tried this but it's not working:
var mainDiv = document.getElementById('container');
var first = mainDiv.getElementsByTagName('div')[0];
first.id = 'one';
You can do it right inside the for loop while it's iterating:
for (i = 0; i < newArray.length; i++)
{
x += '<div id="box-' + i + '"> class="box">' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
You can use assign an ID inside the text string.
Here are a couple of other things you can do to improve this code:
Move the getElementById outside the loop
use js methods instead of string concatenation
Something like this (untested):
// get the container
container = document.getElementById('container');
for (i = 0; i < newArray.length; i++)
{
// create a div
var div = document.createElement('div');
// add attributes
div.setAttribute("id", "box-" + i);
div.setAttribute("class", "box");
// create text node
var textnode = document.createTextNode("This is div #" + i);
// add text to div
div.appendChild(textnode);
// append to container
container.appendChild(div);
}
How about giving it the id when creating? Also put the class=box in quotations like so -> class="box".
And add the whole div construct only once after the for loop. Because right now you are basically overwriting the whole thing multiple times.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
// Change class and add custom id
x += '<div class="box" id="box-'+i+'">' + newArray[i] + '</div>';
}
document.getElementById('container').innerHTML = x; // Add divs after for loop
x = "";
count += 8;
}
Now each box has a unique id going from box-0, box-1, ... to box-n

google apps script web app dynamic list from form

I have a Google Apps Script web app that contains an HTML form with a couple of drop-down lists. When the user submits their choices, a function looks them up in a Google spreadsheet and returns corresponding values in an array. This array could have any length, and I am having trouble getting it to display as an HTML list without having a set list length.
I have this GAS script:
function doGet() {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function discern(formObject) {
var stage = formObject.stage;
var service = formObject.service;
var ss = SpreadsheetApp.openById(ID);
var dataSheet = ss.getSheetByName('Sheet1');
var dataRange = dataSheet.getDataRange();
var data = dataRange.getValues();
var array = [];
for(var i = 0; i < data.length; i++) {
if(data[i][1].indexOf(stage) > -1) {
if(data[i][2].indexOf(service) > -1) {
array.push(data[i][0]);
}
}
}
return array;
}
And this HTML:
<script>
function printList(array) {
var div = document.getElementById('results');
var list = HtmlService.createHtmlOutput('<ul>');
for (var i = 0; i < array.length; i++) {
list.append('<li>' + array[i] + '</li>');
}
list.append('</ul>');
}
</script>
<form id="myForm">
<h3>Farming Stage</h3><br>
Select your farming stage.<br>
<select name="stage">
<option etc etc etc
</select><br>
<h3>Services</h3><br>
Select the service for which you are looking<br>
<select name="service">
<option value= etc etc etc</option>
</select><br>
<br><input type="button" value="Discern"
onclick="google.script.run
.withSuccessHandler(printList)
.discern(this.parentNode)"/>
</form>
<ul id="results"></ul>
(I've replaced some sections with "etc" to save space. The form itself is not the issue.)
Anyway, right now the app returns nothing. Earlier I had the printList function as:
function printList(array) {
var div = document.getElementById('output');
div.innerHTML =
'<ul><li>' + array[0] +
'</li><li>' + array[1] +
'</li><li>' + array[2] +
'</li><li>' + array[3] +
'</li><li>' + array[4] +
'</li></ul>';
}
This version worked, but it was limited to 5 list slots, and the unused slots showed up as "undefined," which was annoying.
Does anyone have any suggestions? Was I close with the 'for' loop in my printList function? Is there another simple way to go about this? I would really appreciate any help or feedback.
Thanks,
Bill
You get the div results do you mean to append the list to the html?
<script>
function printList(array) {
var div = document.getElementById('results');
var list = HtmlService.createHtmlOutput('<ul>');
for (var i = 0; i < array.length; i++) {
list.append('<li>' + array[i] + '</li>');
}
list.append('</ul>');
// ?
div.innerHTML = list.getContent();
}
</script>
edit Also I think you need to getContents of the html Object.
You could not use the HTMLService. Personally I never got it to work the way I wanted it to when I used it. (a couple years ago).
Why not use your loop and just append the string to the div like this.
<script>
function printList(array) {
var div = document.getElementById('results');
var list = '<ul>');
for (var i = 0; i < array.length; i++) {
list += '<li>' + array[i] + '</li>';
}
list += '</ul>';
div.innerHTML = list;
}
</script>
For whatever reason, it worked when I did it this way:
...<br><input type="button" value="Discern"
onclick="google.script.run
.withSuccessHandler(showThings)
.discern(this.parentNode)"/>
</form>
<p>List of services:</p>
<ul id="things">
<li>Waiting...</li>
</ul>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function showThings(array) {
var list = $('#things');
list.empty();
for (var i = 0; i < array.length; i++) {
list.append('<li>' + array[i] + '</li>');
}
}
</script>

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Append an Array to an Unordered List

What I'm trying to accomplish with this code is to output the array alphabet as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <ul id="itemList"></ul>.
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
document.write('<li>' + alphabet[indexNum++] + '</li>');
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
Don't use document.write to do it. You should act like this:
function write_letters(){
var letters = "";
for (var i = 0; i < alphabet.length; i++ ) {
//Also I don't understand the purpose of the indexNum variable.
//letters += "<li>" + alphabet[indexNum++] + "</li>";
letters += "<li>" + alphabet[i] + "</li>";
}
document.getElementById("itemList").innerHTML = letters;
}
More proper way is to use DOM (in case you want full control of what's coming on):
function write_letters(){
var items = document.getElementById("itemList");
for (var i = 0; i < alphabet.length; i++ ) {
var item = document.createElement("li");
item.innerHTML = alphabet[i];
items.appendChild(item);
}
}
You can use a combination of createElement() and appendChild() to add new HTML elements within another HTML element. The code below should work for you:
<html>
<head>
<title>Script Test</title>
</head>
<body>
<ul id="itemList"></ul>
</body>
<script>
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var myElement;
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
// Create the <LI> element
myElement = document.createElement("LI");
// Add the letter between the <LI> tags
myElement.innerHTML = alphabet[indexNum++];
// Append the <LI> to the bottom of the <UL> element
unorderedList.appendChild(myElement);
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
</script>
</html>
Note how the script exists below the body tag. This is important if you want your script to work the way you wrote it. Otherwise document.getElementById('itemList') will not find the 'itemList' ID.
Try to reduce the actions on the DOM as much as possible. Every appendChild on unorderedList forces the browser to re-render the complete page. Use documentFragement for that sort of action.
var frag = document.createDocumentFragment();
for (var i = alphabet.length; i--; ) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(alphabet[indexNum++]));
frag.appendChild(li);
}
unorderedList.appendChild(frag);
So there will be only one DOM action which forces a complete redraw instead of alphabet.length redraws

Categories

Resources