Javascript for loop with array - javascript

Trying to fetch and display data from an array in a for loop but it's only showing one entry. I'm executing this in a trigger for Storyline and when viewing Storyline in the browser I don't get any help from the inspector.
function showInfo(data) {
for (var i = 0; i < data.length; i++) {
var player = GetPlayer();
player.SetVar("name", data[0].name + "\n");
}
}
Seems like something simple to do but not sure whats going on. Perhaps Articulate Storyline adds an extra layer of issues not forseen.

but it's only showing one entry
this is because you're accessing at 0 index for each. You need to use i to correctly iterate over every element.
see:
function showInfo(data) {
for (var i = 0; i < data.length; i++) {
var player = GetPlayer();
player.SetVar("name", data[i].name + "\n");
}
}

Related

How to add for loop inside jquery

i have array of data in mysql database, i want to display it one by one using for loop after getting the results using ajax. the process goes like this.
this is the paragraph where each items going to be rendered
when i try using for loop it says syntax error, unexpected for loop taken, how can i fix this
i.e. here i am using sample for loop in order to make things as easy as possible.
$("#manager_paymentA").html(
'<ul>'+
for(let i=0; i < 5; i++) {
'<li>Hello</li>'
}
+ '</ ul>'
)
You cannot loop inside the html function.
You should store the data into a variable:
var hello = ''
for(let i=0; i < 5; i++) {
hello += '<li>Hello</li>'
}
$("#manager_paymentA").html('<ul>'+ hello + '</ ul>')
You can use jQuery append method.
Example :
$("#manager_paymentA").append("<ul></ul>"); // Create the list
for(let i=0; i < 5; i++) {
$("#manager_paymentA > ul").append("<li>Hello</li>"); // Append elements
}
You can not put the for loop inside the html function and add it between strings.
First build the string in a string variable, and than use that variable in the html function. example:
var html = '<ul>';
for(let i=0; i < 5; i++) {
html += '<li>Hello</li>'
}
html += '</ ul>' ;
$("#manager_paymentA").html();
Just for the sake of proving that creating a string with a loop in-line CAN (somewhat) be done in Javascript:
$("#manager_paymentA").html(
'<ul>'+
(() => {
let s="";
for(let i=0; i < 5; i++) {
s += '<li>Hello</li>'
}
return s;
})()
+ '</ ul>'
)
While this works, it's not really something I would recommend doing.
//data is your array list
data.forEach(item=>
$('#manager_paymentA ul').append('<li>'+item.Name+'</li>');
)
You can access list items with the item element

JavaScript create appropriate number of rows and columns based off of list length

I've been struggling with converting the following C# code into something I can use in JavaScript:
var g = Model.List.GroupBy(r => Model.List.IndexOf(r) / 3).ToList();
It's use was to create the appropriate number of rows, with the appropriate number of columns within them. So for example if the list had 6 elements it would allow me to create 3 rows with 2 columns in it, this was all done in razor pages using the above GroupBy and the below code:
foreach (var parent in g)
{
#Html.Raw("<div class='row'>");
foreach (var item in parent)
{
// populate contents of row
}
#Html.Raw("</div>");
}
However for certain reasons I can't do this in Razor and need to create an alternative in JavaScript but I'm struggling to figure out a way to do this.
Primarily because I don't understand entirely how 'GroupBy' creates the list of groups and what would be a suitable alternative.
Any help, or pointing in the right direction would be great. I've tried a few solutions I found online for creating 'GroupBys' but I couldn't get them to work the way I was expecting. I also thought maybe I could split the original list into a list of dictionaries, but again had little success. I'm possibly missing something obvious.
In the end it turns out I was just missing the obvious answer, I found this excellent SO answer. I had looked at slice but couldn't quite visualise how to use it for my problem (obviously been a long day).
The post showed this snippet:
var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
temparray = array.slice(i,i+chunk);
// do whatever
}
In the end my JavaScript code looked something like this:
var listdata = await octokit.repos.listForUser({ "username": "", "type": "owner" });
var chunk = 2;
var loop = 0;
var tempArray = [];
for (var s = 0; s < listdata.data.length; s += chunk) {
tempArray[loop] = listdata.data.slice(s, s + chunk);
loop++;
}
var htmlString = "";
for (var t = 0; t < tempArray.length; t++) {
htmlString += "<div class='row'>";
var innerArray = tempArray[t];
for (var r = 0; r < innerArray.length; r++) {
var repo = innerArray[r];
htmlString +=
"<div class=\"col-md-6 col-sm-6 col-xs-12\">" +
"<div>" + repocontent + "</div>" +
"</div>"
}
htmlString += "</div>";
}
So with a list that's 6 items long, it gets split into an array that contains 3 lists of 2 items. Then I just create the html string using two for loops to create the outer bootstrap rows and the inner column classes. There's probably a more efficient way to do this but this worked a treat.

Object array gets overwritten by the last object

I have this array of objects being loaded:
$(document).ready(function () {
$("<div></div>").load("/Stats/Contents #stats", function () {
statcount = $(".list-group-item", this).length;
for (var j = 0; j < statcount; j++) {
statList.push(stat);
}
for (var i = 0; i < statcount; i++) {
statList[i].statId = document.getElementById("statId-" + (i + 1) + "").value;
statList[i].productDescription = document.getElementById("productType-" + (i + 1) + "").value;
statList[i].lastMeasuredInventoryAmount = document.getElementById("statLastMeasureAmount-" + (i + 1) + "").value;
}
)}
)}
.... and so on
Then I get the changed values and save them, however, in the ajax post call, all of the array objects are same (the last one assigned), looks like they get overwritten.
Any ideas? I saw these deferred/promise type code but not sure if there's simpler way.
Thanks.
It sounds like you take the statList array and then push that up to the server, with any respective change. Rather than building and maintaining a list like this, have you thought of switching it around and just grabbing the results out of the markup and building up the array at save point?
$("btnSave").on("click", function(e) {
var data = [];
$(".list-group-item").each(function() {
data.push({
statId: $(this).find(".statid").val(),
.
.
})
});
You wouldn't need to give every element an ID (but could) as my sample uses CSS classes to find the element within the current list item. Additionally, if these are inputs, you could serialize them from the root element more efficiently...

how to push string into new array?

I am new to JavaScript and is going through the tutorials here on www.codeacademy.com. I am trying to push a string into a new array however i am getting an error when i run the code
saying
"Oops, try again! It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myWord text appears somewhere in the text variable."
I have looked over the code but have no clue as to where the fault is?
var someText = "This is some text and i am trying to push this text into a new string containing the string text.";
var myWord = "text";
var hits = [];
for (var i = 0; i < someText.length; i++) {
if (someText[i] === myWord[0]) {
for (var j = i; j < someText[i] + myWord.length; j++) {
hits = [];
hits.push("text");
hits[0]; //equals 'text'
}
}
}
any ideas how to get this to work?
You reset hits at each iteration.
Remove hits = [] in your loop.
Your second loop iteration is doing an illegal comparison j < someText[i] + myWord.length;. Remove that someText[i] from the mix and it'll work: j < myWord.length

Print every record of an array on the same page with Javascript

I have an array with a variable amount of records. And I want to print every record of the array in the same html page. I prefer it to display in a list.
I have the following code. However this does only print the last record of the array because it overwrites the previous record in my html ul-element.
for (var i = 0; i < feedbackGeenLid.length; i++)
{
document.getElementById("feedback").innerHTML= ("<li>"+feedbackGeenLid[i] + "</li>");
}
Does anyone have an idea on how to realize this?
Your code keeps replacing the innerHTML you need to add to it.
document.getElementById("feedback").innerHTML += ("<li>"+feedbackGeenLid[i] + "</li>");
^
|
Added + here
For better performance build one string and set it to innerHTML at the end of the loop.
var out = "";
for (var i = 0; i < feedbackGeenLid.length; i++)
{
out += "<li>"+feedbackGeenLid[i] + "</li>";
}
document.getElementById("feedback").innerHTML= out;
Another option, use appendChild()
you are rewriting the content in each loop. use a variable to concatenate the content and then put it in the element:
var html = '';
for (var i = 0; i < feedbackGeenLid.length; i++)
{
html += "<li>"+feedbackGeenLid[i] + "</li>";
}
document.getElementById("feedback").innerHTML= html;

Categories