Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code.

For example:

<div id="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>

<div id="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>

<div id="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>

I am seeking guidance on how to dynamically loop through the contents of this div when a user clicks on a button:

<button id="search" class="btn" value="Search">

I want the contents in this div to be dynamic, negating the need for multiple static divs. How can I achieve this using JavaScript?


EDIT

I am now looking for a way to populate a div with children that match the data from the JSON response below, creating a dynamically loaded list:

[{
    "name": "Malkov Chicken",
    "location": "New York",
    "meals": 5,
    "close_time": 1567289876354
},
{
    "name": "Delicious Chops",
    "location": "San Francisco",
    "meals": 15,
    "close_time": 1567289876354
},
{
    "name": "Banana cultshop",
    "location": "New York",
    "meals": 8,
    "close_time": 1567289876354
}]

The div should populate with data from the JSON list and dynamically create div elements based on the number of responses received from the JSON. For instance, if there are 5 objects in the JSON response, there should be 5 corresponding divs created dynamically.

Answer №1

If you have an array of objects in JSON format, here are the steps you can take:

  • Start by creating a string literal template
  • Utilize the `.map()` method to transform your JSON data into a function called `TPL_Results`
  • Combine the mapped results and insert them into the Document Object Model (DOM)

const restaurants = [{
    "name": "Malkov Chicken",
    "location": "New York",
    "meals": 5,
    "close_time": '23:30'
}, {
    "name": "Delicious Chops",
    "location": "San Francisco",
    "meals": 15,
    "close_time": '22:00'
}, {
    "name": "Banana Cultshop",
    "location": "New York",
    "meals": 8,
    "close_time": '23:00'
}];

const TPL_Results = item => `<div class="Results-item">
  <h3 class="Results-itemName">${item.name}</h3>
  <p class="Results-itemLocation"><b>${item.location}</b></p>
  <p class="Results-itemDetails">Meals: ${item.meals} Close time: ${item.close_time}</p>
</div>`;

document.querySelector("#results")
.innerHTML = restaurants.map(item => TPL_Results(item)).join('');
<div class="Results" id="results"></div>

Answer №2

If you are looking to dynamically add an HTML element on button click, it is important to remember that using a class is preferable over an id since ids must be unique within a document.

You can achieve this by following the example below:

var template = `<div class="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>`;
var occurrences = 3;
document.getElementById('search').addEventListener('click',
function(){
  var strHTML = '';
  for(var i=0; i<occurrences; i++){
    strHTML += template;
  }
  document.getElementById('container').insertAdjacentHTML('beforeend', strHTML);
});
<div id="container"></div>

<button id="search" class="btn" value="Search">Create</button>

Update:

var listArr = [{
    "name": "Malkov Chicken",
    "location": "New york",
    "meals": 5,
    "close_time": 1567289876354
},{
    "name": "Delicious Chops",
    "location": "San francisco",
    "meals": 15,
    "close_time": 1567289876354
},{
    "name": "Banana cultshop",
    "location": "New york",
    "meals": 8,
    "close_time": 1567289876354
}];
document.getElementById('search').addEventListener('click',
function(){
  var strHTML = '';
  listArr.forEach(function(item){
    strHTML += `<div class="Results-item">
            <h4 class="Results-itemName">${item.name}</h4>
            <p class="Results-itemLocation"><b>${item.location}</b></p>
            <p class="Results-itemDetails">Meals: ${item.meals} Close time: ${item.close_time}</p>
            </div>`;
  })
  document.getElementById('container').insertAdjacentHTML('beforeend', strHTML);
});
<div id="container"></div>
<button id="search" class="btn" value="Search">Create</button>

Answer №3

If you want to add multiple cards with the same content, you can create a template for one card in JavaScript and then append several of these cards to a container div.

To add multiple divs with the same content upon button click, generate the string outside of the click event using a for loop, and then append the generated string.

In this example, the container div is named .content. Remember that each element should have a unique ID and IDs should not be repeated.

Check out the working example below:

let card = 
  `<div class="card">
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4d5c5c4049015843594f4401454f43426c1e025c424b">[email protected]</a>?v=73d79a89bded" class="card_img" alt="result image">
    <h4>OFFLINE</h4>
    <p>Yes!!</p>
   </div>`;

let amount = 10; // number of cards to add on button click
let toAppend = '';
for (let i = 0; i < amount; i++) {
  toAppend += card;
}

$("#search").click(function() {
  $('.content').empty().append(toAppend);  
});
img {
  height: 150px;
  width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="content"></div>
<button id="search" class="btn" value="Search">Click me</button>

In response to your revised question:

You can iterate through your data array using .reduce and build a string containing individual divs using template literals and destructuring. After that, you can append this constructed div to your body or a div (in this case it's appended to a div with the class content).

let data = [{
    "name": "Malkov Chicken",
    "location": "New York",
    "meals": 5,
    "close_time": 1567289876354
  },
  {
    "name": "Delicious Chops",
    "location": "San Francisco",
    "meals": 15,
    "close_time": 1567289876354
  },
  {
    "name": "Banana Cultshop",
    "location": "New York",
    "meals": 8,
    "close_time": 1567289876354
  }
];

let html = data.reduce((acc, {name, location, meals, close_time: close}) =>
      acc += `
      <div class='item'>
        <p>${name}</p>
        <p>${location}</p>
        <p>${meals}</p>
        <p>${close}</p>
      </div>`
, ``);

$('.content').append(html);
.item {
  border: 1px solid black;
  margin: 10px 0;
}
p {
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content"></div>

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

Is there a way to set the background of the first sibling element to blue, but change it when another sibling element is hovered over?

I have a list of names: <div>Timothy Gruns</div> <div>Lawrence Fishly</div> <div>Jackson Crolya</div> What I want is for the background color to change to blue when any name is hovered over. However, if no names are be ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

Initialize React Native project

Which ruby command shows the path to Ruby: /Users/User/.rbenv/shims/ruby Ruby -v command displays the version of Ruby installed: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21] Which bundle command reveals the path to Bundler: /Users/Us ...

Unable to disable webpack HMR

I have set up my project using express version 4.14.0, webpack version 1.14.0 with babel and its presets. I obtained this sample webpack configuration from a reliable source: var path = require('path'); module.exports = { entry: './main. ...

The feature of Switch css does not appear to function properly when used in conjunction with input type

Why does the switch button not work with the input type radio but works with a checkbox button? How can I maintain the radio input and solve this issue? @charset "utf-8"; /* CSS Document */ /* ---------- GENERAL ---------- */ body { background: #4a4a4 ...

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

Using jQuery Ajax to send data and retrieve responses in the Codeigniter framework

I am struggling with passing values in CodeIgniter and I need some guidance. Could you provide an example code snippet using CodeIgniter to send a value from a view to a controller using Ajax and jQuery, and then display the result on the same page? In my ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Unusual perspective of JSON with ng-jsoneditor in AngularJS

Currently, I have integrated ng-jsoneditor into my AngularJS application to display and format JSON data. I found guidance on how to implement this from both here and here. Here is the HTML code snippet: <div ng-jsoneditor="onLoad" ng-model="vm. ...

Arrange ten objects in each of the four JavaScript arrays in ascending order based on a specific value

model with sample data -> [{ date: '13413413', name: 'asdfasdf', other: 'kjh' }] The getJSON function returns 4 arrays, each containing 10 model objects. array1 = 10 resultsObj sorted by date from newest to o ...

In Node.js, JavaScript, when using SQLite, the variables are inserted as Null

I have spent a lot of time searching and trying various methods, but I am still unable to solve this issue. My goal is to insert 8 variables received from an API call into an SQLite table. Although the execution seems correct, when I query the table, all v ...

Fade in/out overlay effect when clicking on a content block

I've hit a roadblock while trying to implement overlay fading in and out to cover a block created by some JavaScript code. Here is a link to the project. When you click on any of the continents, a series of blocks with country flags will appear. You& ...

What is the most effective way to identify mobile browsers using javascript/jquery?

As I develop a website, I am incorporating image preloading using JavaScript. However, I want to ensure that the preload_images() function is not called for users on slow bandwidth connections. In my experience, the main demographic with slow internet spe ...

I am looking to efficiently store various pieces of data in a database by utilizing a singular variable through JS, PHP, and AJAX for streamlined processing and management

I am not very familiar with the technical jargon in programming, so please bear with me if my question is a bit unclear. To provide more clarity, I have shared the code that I have already written. I will elaborate on the issue after presenting the code: ...

jqGrid is failing to display basic JSON data properly

As a newcomer to Jquery and Json, I am struggling with binding a JSON object from a RESTful Webservice written in WCF to jqGrid. Despite saving the JSON object as a static file and attempting to bind it to the grid, I realized that the issue does not lie w ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

In the realm of numeric input in JavaScript (using jQuery), it is interesting to note that the keyCode values for '3' and '#' are identical

I am in need of setting up an <input type="text" /> that will only accept numeric characters, backspace, delete, enter, tabs, and arrows. There are many examples out there, and I started with something similar to this: function isNumericKeyCode (ke ...

Generate an HTML webpage with dynamic content using MySQL

How can I display data from a MySQL table on an HTML page? The content in my table includes various rows that I would like to show separately on the web page. This is the structure of my table: I envision the web page layout to showcase each row individ ...

The onClick function for the "div" element is failing to append

I am currently working on a project that involves searching for strings in a database and then appending the selected string to a text box. So far, I have been successful in retrieving the search results from the database and appending them below the text ...

The process of combining a CssStyleCollection with a System.Web.UI.WebControls.Style

I am working with a list item and trying to apply styles using System.Web.UI.WebControls.Style. However, I noticed that there isn't a MergeStyle option similar to what's available for controls. Instead, there is an Attributes.CssStyle property of ...