V
V
Vpolotske2018-12-16 20:28:45
JavaScript
Vpolotske, 2018-12-16 20:28:45

How to add values ​​from json to identical divs?

In general, there is code for adding values ​​from json to div blocks:

$(document).ready(function(){
  $.ajax({
        url: 'ajax/prop',
    dataType: 'html',
        success:function(data){
    var jsonStr = JSON.parse(data);
 const container= document.getElementById('prop');
  jsonStr.forEach(function(item) {
  const itemDiv = document.createElement('button');
  itemDiv.classList.add('btn');
  itemDiv.id = item.id;
  let innerHtml = '<dl>';
  Object.keys(item).forEach(function(key) {
    innerHtml += `
      <dd>${item[key]}<dd>
    `;
  });
  innerHtml += '</dl>';
  itemDiv.innerHTML = innerHtml;
  container.appendChild(itemDiv);
});
}
});


But the problem is that all values ​​are added only to the first div, and I need the first value from json to be added to the first div, the second to the second, and so on.
Here is a line from json.
{"id":"1","time":"2 минуты"},{"id":"2","button":"Купить"},{"id":"3","back":"Вернуть"},{"id":"4","time":"1 минута"}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
evkochurov, 2018-12-16
@evkochurov

"If the names are wrong, everything is wrong" (c)
In the code for half of the variables, the name does not match the content. Accordingly, it is not clear what you mean by "first div": container or itemDiv (which is actually a button, not a div)?
Show with your hands the assembled HTML that you want to get as a result of the script, if you submit the given json as input.

A
Alexander, 2018-12-18
@lebonnet

var let const
document.getElementById and Jquery...
as far as I can see you don't understand what you are writing at all.
How it should work there is also not clear (it’s better to type everything on jsfiddle.net with json data, and show how it works, and what are the expectations), but the source code should look something like this:

$.ajax({
    url: 'ajax/prop',
    dataType: 'html',
    success: function (data) {
        let $container = $('#prop');
        JSON.parse(data).forEach(item => {
            let html = '<dl>';
            Object.keys(item).forEach(key => html += `<dd>${item[key]}<dd>`);
            html += '</dl>';
            $container.append(`<button class="btn" id="${item.id}">${html}</button>`);
        });
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question