For loop repeats each loop onto the next - javascript

I am trying to dynamically adjust the document.getElementById(divID) by using a loop. This seems to work...sorta
It keeps looping as you will see in the screenshot below.
let searchresult = function(response) {
let output ="";
for (let j = 0; j < response.length; j++) {
let divID = response[j].resortcode + 'results';
let container = document.getElementById(divID);
output +=
`
<div class="${response[j].resortcode} ${response[j].roomcode}">
</div>
`;
console.log(container);
$(container).html(output);
}
};
I have my container div set to the response[j].resortcode but I thought by using document.getElementById(divID) that it would only allow that resort code inside of a div with a corresponding resortcode
Notice it is also looping the getElementByID more than once.
I would like the output going to a premade div id in my html file (which it does, it just keeps repeating). Then loop the results <div class=${response[j].resortcode}"></div> into the corresponding premade div. Here is a photoshopped version of the desired result:
EDIT: Adding console of original response.
Any help is greatly appreciated.

Your variable output is added upon every iteration and never reset, so when you set the html to output, it contains every previous iteration.
You can fix this by getting the innerHTML and adding onto instead of having an output variable.
You can also store the resortcode into a Set (a special kind of array that does not allow duplication of elements) and then console.log out those containers at the end.
let searchresult = function(response) {
let resortCodes = new Set();
for (let j = 0; j < response.length; j++) {
resortCodes.add(response[j].resortcode); // add only happens if the resortcode isn't already in resortCodes
let divID = response[j].resortcode + 'results';
let container = document.getElementById(divID);
container.innerHTML += `
<div class="${response[j].resortcode}">
<div class="roominfo"><p class="roomtitle"> ${response[j].roomname} - ${response[j].viewname}</p>
</div>
</div>
`;
}
resortCodes.forEach(function (resortCode) {
console.log(document.getElementById(resortCode + "results"));
};
};

Related

Change text Inside heading with info from Array

I'm making a fetch call to retrieve some data on player cards.
I'm trying to display said cards and running into issues accurately parsing JSON and showing info in HTML.
Here is an example HTML heading for a card:
<h3 class="card__title">Example Card</h3>
Here is some JavaScript code I used after the fetch call:
let cardList = json.results
let cardTitle0 = cardList[0].name.toString();
How do I change the text from Example Card -> cardTitle0 from my array? This question applies to other attributes from the array and HTML objects.
You'll need to use the h3 element to get the link:
const link = document.querySelector(".card__title a");
// These can be const.
const cardList = json.results
const cardTitle0 = cardList[0].name.toString();
link.innerHTML = cardTitle0;
For multiple cards, you'd have to loop through the cardList json result and also through the elements on the page.
This is just an idea off the top of my head so I can't verify this code works or is even the best option for addressing multiple cards but hopefully it'll get you going in the right direction.
const links = document.querySelectorAll(".card__title a");
const cardList = json.results;
// Loop through the links on the page.
for (let i = 0; i < links.length - 1; i++)
{
for (let j = 0; j < cardList.length - 1; j++)
{
const title = cardList[j].name.toString();
links[i].innerHTML = title;
}
}

an addition list element is added to the browser after i add an unordered list from JS

let leadTracker = ["bbboo","hjkku","hhythjm"];
console.log(leadTracker)
let inputText = document.getElementById("input-text");
let inputButton = document.getElementById("input-button");
let Listing = document.getElementById("listings");
function clicker() {
leadTracker.push(inputText.value);
for(let i = 0; i < leadTracker.length; i++) {
Listing.innerHTML += "<li>" + leadTracker[i] + "</li>";
}
}
just practicing a fw things on javascript but i seem to be having an issue with adding an unordered list to my html from JS. so basically the list is added but an addition li element
is added anytime i try to open it on my browser. I have cosole.logged leadTracker and get that
my array length is 3. Please what can I do?

Javascript For loop appending child only appends first element, then throws error

I'm looping through a js object with a nested for loop, stated below, it appends the first element correctly, but then throws the following error:
Can't set the property className of an undefined reference or empty reference. (not sure if exact error, translating from Dutch...)
function allVideos() {
var sql = "SELECT videos.VideoName, videos.VideoPath FROM videos";
var resultSet = db.query(sql, {json:true}); //returns: [{"VideoName":"timelapse aethon2","VideoPath":"videos\\Roermond Papier\\160424 Time laps Aethon2.avi"},{"VideoName":"timelapse aethon3","VideoPath":"videos\\Roermond Papier\\160424 Time laps Aethon2.avi"}]
var parsed = JSON.parse(resultSet);
var parsedlength = arrLenght(parsed);
//alert(resultSet);
for(var i = 0; i < parsedlength; i++) {
var obj = parsed[i];
//alert(i);
var videoElement = document.getElementById("allVideos");
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
videoElement.appendChild(document.createElement('div'));
videoElement.children[i].id='allVid' + i;
videoElement.children[i].className='col-md-4 col-xs-12';
//alert(typeof key)
var card = document.getElementById('allVid' + i);
alert(i);
card.appendChild(document.createElement('div'));
card.children[i].className='card card-block';
card.children[i].innerHTML = "<h3 class='card-title'>" + obj['VideoName'] + "</h3><button class='btn btn-primary'>Selecteren</button>"
}
}
}
}
[EDIT] added screenshot of how it looks
Your code has some significant logic issues. You're using nested loops, but appending to an element assuming that the outer loop counter will let you index into that element's children to get the element you just appended. Later, you try to get that same element again using getElementById. Then, you append a new element to your newly-created element, but try to access that new element using children[i] on the one you just created — at that point, the card element will only have a single child, so as of the second outer loop, it will fail.
createElement returns the element to you, so there's no reason at all to try to access it via children[i] (either time) or getElementById.
See comments:
function allVideos() {
var sql = "SELECT videos.VideoName, videos.VideoPath FROM videos";
var resultSet = db.query(sql, {json:true});
var parsed = JSON.parse(resultSet);
var parsedlength = arrLenght(parsed);
for(var i = 0; i < parsedlength; i++) {
var obj = parsed[i];
//alert(i);
var videoElement = document.getElementById("allVideos");
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// Create the card, give it its id and class
var card = document.createElement('div');
card.id='allVid' + i;
card.className='col-md-4 col-xs-12';
// Create the div to put in the card, give it its class and content
var div = document.createElement('div');
card.appendChild(div);
div.className='card card-block';
div.innerHTML = "<h3 class='card-title'>" + obj['VideoName'] + "</h3><button class='btn btn-primary'>Selecteren</button>"
// Append the card
videoElement.appendChild(card);
}
}
}
}
Side note: arrLenght looks like a typo (it should be th, not ht), but moreover, there's no reason to use a function to get the length of an array; it's available via the array's length property: parsedLength = parsed.length.
Side note 2: You may find these ways of looping through arrays useful.
Your problem is the if within the nested for:
if(obj.hasOwnProperty(key)) { ...
The variable i is increased even if the property is not "owned" (when the if condition returns false), so next time that the condition is true, i is out of bounds.

For loop to Iterate through an array and create divs that are siblings of each other

I am trying to get my game2 element to have two child divs containing the contents of the gameTwo array, but what is happening in this script is that the first time it iterates through the loop, it creates the child div I want, but the second time it creates a child of the child. Can someone advise on how I can edit this so that the divs are both siblings of each other?
var gameTwo = ['Kansas', 'Villanova']
var gameTwoText = '';
for (i = 0; i < gameTwo.length; i++) {
gameTwoText += "<div>" + gameTwo[i];
}
var secondGame = document.getElementById('game2').innerHTML = gameTwoText;
You need a closing tag on each div - try:
gameTwoText += "<div>" + gameTwo[i] + "</div>";
Without the </div>, you never close the first div so each subsequent one is created as a child of the last.
As others have said, make sure you close your DIV tag in the loop, however you can always do this the old fashion way which will build the elements via the DOM:
var secondGame = document.getElementById('game2');
var gameTwo = ['Kansas', 'Villanova'];
var div = null;
for (var i = 0, len = gameTwo.length; i < len; i++) {
div = document.createElement('div');
div.appendChild(document.createTextNode(gameTwo[i]));
secondGame.appendChild(div);
}

Javascript: assigning button id as a number inside of an innerhtml

I have this problem, where I can't seem to put the number of the "xq" into being the id for the buttons while using innerHTML.
Here's the code:
for (var xq = 0; xq < 3; xq++) {
var pass = xq;
tabletextvar = '<button id="buttontexto"; onclick="cancelObject(this.id);">Button</button>'
document.getElementById("buttontexto").innerHTML = pass;
}
document.getElementById("tabletext").innerHTML = tabletextvar;
Button ID ends up being "buttontexto" when I really want it to be what innerHTML. It could be that you can't have another innerHTML inside an innerHTML.
Any tips or fixes would be appreciated
If you want to have 3 buttons with id 1,2 and 3 then you need to append them, just using a variable inside the loop will override it and when the loop is over it will have the last value. You need to have a concatenated string.
var buttons = [];
for (var xq = 0; xq < 3; xq++) {
buttons.push('<button id="',xq,'" onclick="cancelObject(this.id);">',xq,"</button>")
}
document.getElementById("tabletext").innerHTML = buttons.join('');
Demo: Fiddle

Categories

Resources