1

Really just seems simple enough: been following the jquery docs; can't reason why this won't print a list to the specified div element.

$(document).ready( function() {
	$.getJSON("dino.json", function(data) {
		 $.each(data, function(key, val) {
			$("#triassic").html("<li class = " + key.name + ">" + key.name + "</li><br>") 
                 });
         });
});
<!DOCTYPE html>
<html lang = "en">
<head>
<title>TEST</title>
<!-- my Script -->
<script src="dinoscriptTest.js"></script>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id = "triassic"></div>
</body>
</html>

JSON:

[
{
"name":"T REX"
},
{
"name": "Triceratops"
},
{
"name": "Diplodocus"
}
]

2 Answers 2

2

In your $.each(), your key is actually the index. Instead you should be pulling name from your variable val.

Sign up to request clarification or add additional context in comments.

Comments

2

There are two mistakes in your code.

  1. key.name, key is the index of the array. Please try val.name
  2. $("#triassic").html("<li class = " + key.name + ">" + key.name + "</li><br>"), in each iteration, the div's content will be replaced. Please try $("#triassic").append("<li class = " + val.name + ">" + val.name + "</li><br>") });

Instead use,

$(document).ready( function() {
    $.getJSON("dino.json", function(data) {
         $.each(data, function(key, val) {
            $("#triassic").append("<li class = '" + val.name + "'>" + val.name + "</li><br>") 
                 });
         });
});

Regards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.