0

I'm getting a list of objects and printing their content in the HTML page dynamically but only the last object is getting printed in all the added divisions. Here is the js code:

var thelist = JSON.parse(sessionStorage.getItem("suspectList"));
for (var k in thelist) {
    $(document).ready(function () {
        $('#outerdiv').append('<div class="card"><h5 class="card-header">' + 'Crime: ' + thelist[k]['crime'] + '</h5><div class="card-body"><h5 class="card-title">' + 'Suspect name : ' + thelist[k]['name'] + '</h5><p class="card-text">' + 'Date of birth: ' + thelist[k]['dob'] + '</p><a href="#" class="btn btn-primary">Enter Statement</a></div></div>');
    });
    console.log(thelist[k]['name'] + ' ' + thelist[k]['phone'] + ' ' + thelist[k]['dob']);
}

Here is the output:

enter image description here

Here is the console log

enter image description here

Rahul Choudhary
  • 309
  • 3
  • 12
  • 2
    Anyway use `let` instead of `var`. Otherwise, your `k` points to the same value everytime, which is the last element. – Tushar Shahi Jul 21 '21 at 19:22
  • 1
    Does this answer your question? [Get values from same class buttons](https://stackoverflow.com/questions/68467735/get-values-from-same-class-buttons) – Tushar Shahi Jul 21 '21 at 19:22
  • 1
    Why do you have `$(document).ready()` inside of your loop?? Wrap it around all of your code instead of inside the for loop – BeerusDev Jul 21 '21 at 19:23
  • @TusharShahi Thank you very much, this solved the problem. What would my life be without StackOverflow!! – Rahul Choudhary Jul 21 '21 at 19:26

0 Answers0