Is it possible to display all the outcomes of a JavaScript loop?

Feeling a bit confused here. As a newcomer to JavaScript/jQuery, I decided to create a loop that would cycle through some JSON data:

  <script type="text/javascript">
   var geturl = "http://couponsforweed.com/?json=get_recent_posts";

            $.ajax({

                type:'GET',
                url:geturl,
                complete: function(){                    
                },
                success: function (data) {

                    var response = data; //JSON.parse(data);

                    // Success!
                    alert("status: " + response.status + "\ncount: " + response.count + "\npages: " + response.pages + "\ncount_total: " + response.count_total + "\nposts: " + response.posts.length);


                    //loop through posts
                    for(var i = 0; i != response.posts.length; i++) {

                        //get each element in the array
                        var post = response.posts[i];


                        // displaying results to see what's happening
                        output.innerHTML = i + " post: " + post.custom_fields.schemaState;

                    }


                },
                error:function (xhr, ajaxOptions, thrownError) {                    
                    alert("Error");

                }

            });
  </script>

The code seems to be working fine, and I'm proud of myself for making it work. However, there's one issue bothering me:

// Displaying results to see what's happening
   output.innerHTML = i + " post: " + post.custom_fields.schemaState;

Why does this only show me the last result in the loop instead of all the results in a list?

Currently, I am getting:

9 Ca

What I'm aiming for is (each result in the loop):

1 Ca 2 Ca 3 Ca 4 Ca 5 Co 6 Wa 7 Co 8 Ca 9 Ca

In PHP loops within WordPress, you can iterate through all the fields of each post and retrieve the results accordingly. It seems a bit different in JavaScript.

Answer №1

Instead of constantly overwriting the output.innerHTML in each iteration, try using the += operator to append to the variable without replacing it entirely. Another suggestion is to create an interim variable like 'foo' and continuously add to it within the loop, then updating the output HTML at the end of the loop for better efficiency.

Answer №2

It is advisable to use "+=" for appending rather than "=" at this point:

output.innerHTML = i + " post: " + post.custom_fields.schemaState;

By following this recommendation, the line will appear as follows:

output.innerHTML += i + " post: " + post.custom_fields.schemaState;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty with Bootstrap buttons functioning correctly within a React environment

I am currently working on creating a responsive navigation bar in React. One issue I am facing is that when I zoom in on the page, the links disappear and are replaced with a button that triggers a drop-down list with the links. However, when I click on t ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

Is it feasible to trigger a modal to open from a source external to the Vue

How can a component be made reusable by calling a method from outside the component? Currently, I include a button to open the modal in a template slot: index.php <modal> <template slot="button"> <button class="btn">Open mo ...

The MUI Module is missing: Unable to locate '@emotion/react'

Attempted this solution, but unfortunately it did not work Currently using the latest version of Material-UI Error: Module not found: Can't resolve '@emotion/react' Let's try installing it then.. npm i @emotion/react @emotion/style ...

Mastering Angular Protractor for End-to-End Testing

Currently working on an end-to-end test for my Angular application using Protractor. While I can mock httpBackend for unit tests, I prefer to make actual server calls and test against the JSON response. Despite researching on stackoverflow, I'm still ...

Stop allowing special characters in Ajax requests (HTTP)

$.ajax({ url: '/pos/' + myVar type: 'GET', success: function(data) {} .. I have a variable called myVar with a value of "a-b". However, the value may sometimes be represented as "a->b", causin ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

Unlock the secret to retrieving specific properties from a JSON object

Whenever this code is executed: import requests import json def obtain_sole_fact(): catFact = requests.get("https://catfact.ninja/fact?max_length=140") json_data = json.loads(catFact.text) return json_data['fact'] print(obtain_s ...

What is the process for recursively extracting specific fields from json data?

Underneath is a sample json document or json variable that I'm working with in python to extract specific fields. Any guidance on how to accomplish this task would be greatly appreciated. json_variable = { "server01":{ "addr ...

Tips on Extracting Data from a JSON Object with an Embedded Array

Check out this example of a Json Object: {"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null} He ...

Having trouble connecting to JSTL in my JavaScript file

Currently, I am facing an issue with my JSTL code that is housed within a JavaScript file being included in my JSP page. The problem arises when I place the JSTL code inside a script within the JSP page - it works perfectly fine. However, if I move the s ...

Updating a SharePoint list item by retrieving a field value from a people picker field

I am attempting to update an SP.Listitem by replacing an spUser with another user using JSOM. Below is the code snippet: // Query the picker for user information. $.fn.getUserInfo2 = function () { var eleId = $(this).attr('id'); var siteUrl ...

A CSS rule to display a nested list on the left-hand side

I created a menu that you can view here. When hovering over "tanfa demo example," the sublist appears on the right side. The issue I'm facing is that my menu is positioned all the way to the right, which means the sublist also appears on the extreme ...

nlohmann: Sending and receiving JSON data via a TCP socket

Currently, I am working on a project that involves converting JSON data to raw format and then outputting it to a file. After conducting some research, I came across the following code snippet: #include <iostream> #include <nlohmann/json.hpp> ...

The email protected function is failing to display components and is not generating any error logs

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05776064667128776a7071607728616a6845332b31">[email protected]</a> seems to be having trouble rendering components. I've been away from React for a bit and now I ...

Customize Prices for Attributes in Woocommerce?

My Woocommerce product has numerous attribute fields. For instance: I run a shop that specializes in engraved stones, each stone can have a maximum of 10 letters. With 26 letters in the alphabet, the base cost of the stone is $3 with no engraving. Each le ...

What is the process for extracting dates in JavaScript?

I need help extracting the proper date value from a long date string. Here is the initial date: Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time) How can I parse this date to: 2020-08-30? Additionally, I have another scenario: Tue Aug 25 ...

Tips for keeping an image stationary when hovering over it

I'm in need of some assistance. Despite my best efforts, I have been unable to achieve the desired outcome. I am looking to create a scenario where an image remains in place even when the mouse hovers over it. Essentially, I want the image to stay vis ...

Does the language setting on a browser always stay consistent?

Using javascript, I am able to identify the language of my browser function detectLanguage(){ return navigator.language || navigator.userLanguage; } This code snippet returns 'en-EN' as the language. I'm curious if this i ...

Providing real-time results as numbers are added together

I need assistance in calculating a price inclusive of VAT based on a user-entered VAT rate. Is it possible to show the result in an input box dynamically as the user inputs the VAT rate and price, without requiring them to click a button or resubmit the fo ...