Implement a loop using $.each along with conditional statements utilizing if with $.getJSON

Struggling with the usage of $.each and unable to figure out how to properly print all the data from my JSON file. Additionally, I've encountered issues with the if statement as well - no matter what approach I take, I can't seem to get any data printed.

Here's a snippet from my JSON file:

[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]

Below is my $.getJSON script:

<script type="text/javascript">
    function read_json() {
        $.getJSON("home.json", function(data) {
            var el = document.getElementById("kome");
            el.innerHTML = "<td><a href=" + data.link + " data-ajax='false'><img src=" + data.img + "><div class='dsc'>" + data.expo + "<br><em>" + data.datum + "</em></div></a></td>";
        });
    }
</script>

Any suggestions on how I can integrate the $.each statement effectively and troubleshoot the if statement?

Answer №1

Give this a go

$.getJSON("home.json", function (data) {
    var html = '',
        element = document.getElementById("kome");
    $.each(data, function (key, value) {

         html += "<td><a href=" + value.link + " data-ajax='false'><img src=" + value.img + "><div class='dsc'>" + value.expo + "<br><em>" + value.datum + "</em></div></a></td>";
    });
    element.innerHTML = html;
});

Answer №2

Is this similar to what you're looking for?

<script type="text/javascript>
    function read_json() {
        $.getJSON("home.json", (data) => {
            let html = '';
            data.forEach((record, i) => {
                html += '' +
                '<td>' +
                    '<a href="' + record.link + '" data-ajax="false">' +
                        '<img src="' + record.img + '">' +
                        '<div class="dsc">' +
                            record.expo + '<br>' +
                            '<em>' + record.datum + '</em>' +
                        '</div>' +
                    '</a>' +
                '</td>';
            });
            $('#kome').html(html);
        });
    }
</script>

Please note: I have not tested this code personally, so there may be some syntax errors, especially regarding the quotation marks in string concatenation.

It's worth mentioning that you can achieve the same result using a simple for-loop instead of jQuery's $.each:

for (let i = 0; i < data.length; i++) {
    let record = data[i];
    // do something...
}

If you are working with elements in the DOM, then jQuery's .each() method is quite handy. For instance, if you need to iterate over elements with the 'dsc' class, you can do:

$('.dsc').each((i, dsc) => {
    // Perform actions on the $(dsc) element.
});

Furthermore, since you are already using jQuery, it would be best to utilize jQuery's selectors like $('#kome').

For more detailed examples and information, refer to jQuery's official documentation.

Answer №3

When using $.each, keep in mind that it can iterate over arrays [] or objects {}. If your JSON data contains both types, start by handling the array first to access the object within each iteration. For more information, refer to the jQuery each documentation.

Another important point to remember is when appending to innerHTML, make sure to use "+=" instead of "=" to avoid resetting the HTML content during each iteration.

var element = document.getElementById("kome");
$.getJSON('ajax/test.json', function(data) { 
    $.each(data, function(index, linkData) {
        element.innerHTML += '<a href="' + linkData.link + '">' + linkData.expo + '</a>';
    });
}

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

Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Val ...

Json File containing a Listbox

I am encountering an issue with my json file where the listbox items I highlight and save are not highlighted when loaded again. How can I ensure that the selected items remain highlighted so I can easily change my item selection? THE CODE: import tkinter ...

The process of assigning a function to an object in JavaScript is currently not functioning properly

After updating a Vue2 project to Vue3, I ran into an issue with Javascript. It seems that the language now prevents me from assigning a function to an object. In the code below, I define a function "bar" within a loop. While I can successfully call the fu ...

What is the ideal event to trigger a response when the user completes entering text into the search field in Vue.js?

I am currently utilizing a text field from the Vuetify library to filter a table within my application. <v-text-field style="min-width: 300px;" v-model="filterString" label="Search" /> The functionality is straigh ...

Bring in the Stencil JS library from a separate Stencil JS library

Within my collection of Stencil JS web components, I have two distinct libraries - library-a and library-b. These are not complete applications, but rather separate npm packages containing various components. I am interested in incorporating certain compo ...

Select: Exchange icon when clicked

UPDATE MENU ICON jsfiddle.net/a3MKG/83/ Can someone provide guidance on how to change the menu icon image upon clicking it? I would like the icon to switch to a different image (such as an X) once it has been clicked. Please Note: When the menu icon is c ...

Concealing a div based on a condition

Having difficulty concealing a div once a specific condition is met. The condition depends on the user logging into a web application. In my CSS file, I have set the multipleBox div to visibility: hidden, along with other styling attributes like border co ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Looking to pass multiple props and run a function for each one? Here's how!

There is a scenario where I have two separate times in minutes format that need to be converted to 24-hour format without separators. I am currently using a function for this conversion and then using momentjs to transform it into the required format. Whil ...

Is there a way to obtain the guild ID during the createGuild event?

Can someone please help me figure out how to get the guild id in the event guildCreate.js? I have tried using guild.id but it returns undefined. Even when I use console.log(guild), it shows a blank space. Using client.guild.id throws an error for id. cons ...

Replicate styling while copying CodeMirror code

Is there a way to maintain the styling and formatting of javascript code when copying from CodeMirror? Whenever I try to copy and paste from the CodeMirror editor, the coloring and style are lost, with the content pasted as text/plain. How can I preserve ...

What are the advantages of retrieving a complete category tree, including all categories and sub-categories, versus retrieving only the necessary branches as required?

My query is not centered around terminology accuracy, but rather on the goal of presenting a tiered structure consisting of categories, sub-categories, and sub-subcategories. In total, there are approximately 100 different categories and their respective ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Transform jQuery code into vanilla JavaScript

I'm struggling with converting this part of code from jQuery to plain JavaScript. I've documented everything in a JSFiddle as an illustration. The following is the script: $(".button").click(function () { $pageID = $(this).attr('name& ...

The app is having trouble loading in Node because it is unable to recognize jQuery

I am currently using Node to debug a JavaScript file that includes some JQuery. However, when I load the files, the $ sign is not recognized. I have installed JQuery locally using the command npm install jquery -save-dev. The result of "npm jquery -versio ...

The module 'react/jsx-runtime' could not be located within the path relative to '@mui/styled-engine/StyledEngineProvider/StyledEngineProvider.js'

I encountered this issue when attempting to create a new React project using MUI. I followed this code example from the documentation, which functions correctly in their live Codesandbox but not on my local setup. Here is the complete error message: Module ...

Is your div not loading correctly due to JQuery or Javascript?

PHP Version 7.0 JQuery Version 3.1.0 It is noticeable that the content above gets copied and pasted every five seconds instead of refreshing. The aim is to refresh the include every five seconds. Website: Code: <!doctype html> <html><h ...

Using Next.js Link prefetch feature can lead to unexpected 404 errors on a production website

I'm currently working on a Next.JS blog project where I have created a page to showcase all of my articles. When I render the component, it appears like this: <div> {articles.map((article, index) => { const path = `/magazine/${ar ...

Tips for effectively utilizing foreach loops in JQuery

I've encountered an issue while displaying a list of data in a table using Smarty templates and foreach loops. I'm trying to make each line clickable to show new data below it, but currently, this functionality only works for the first line. Is t ...

Prevent the page from scrolling while the lightbox is open

I am struggling with a lightbox that contains a form. Everything is functioning properly, but I need to find a way to prevent the HTML page from scrolling when the lightbox is active. <a href = "javascript:void(0)" onclick=" document.getElementById(& ...