Reputation: 25
I am wondering when I loop the assoc array in my html file return only first value not all assoc array, but when I view it in console.log its working correctly but when I print it in HTML no error but not all data will loop.
How to process print completely LOOP all the data from associated of array to html using javaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<p id="mypanel"></p>
<script>
var dataRequest = [
{
"place": "Visaya",
"countryCode": "PH",
"region": "Calabarzon",
"latitude": "14.5666700",
"longitude": "121.0333300",
"distanceMiles": 0.37,
"distanceKilometers": 0.59,
"directionAngle": 27.84,
"directionHeading": "NNE"
},
{
"place": "Tejeros",
"countryCode": "PH",
"region": "Calabarzon",
"latitude": "14.5666700",
"longitude": "121.0333300",
"distanceMiles": 0.37,
"distanceKilometers": 0.59,
"directionAngle": 27.84,
"directionHeading": "NNE"
},
{
"place": "Bancal",
"countryCode": "PH",
"region": "Calabarzon",
"latitude": "14.5666700",
"longitude": "121.0333300",
"distanceMiles": 0.37,
"distanceKilometers": 0.59,
"directionAngle": 27.84,
"directionHeading": "NNE"
}
];
dataRequest.forEach(function(value, index) {
var text = ` Place : ${value.place} <br />
val1 : ${value.countryCode} <br />
val2 : ${value.region} <br />
val3 : ${value.latitude} <br />
val4 : ${value.longitude} <br />
val5 : ${value.distanceMiles} <br />
val6 : ${value.distanceKilometers} <br />
val7 : ${value.directionAngle} <br />
val8 : ${value.directionHeading} <br />`;
// place to my HTML but not looping all data why??
document.getElementById("mypanel").innerHTML = text;
// with console all dataRequest will loop
console.log(text);
});
</body>
</html>
Here' image that result for that script:
Result: https://www.screencast.com/t/1F7zyUcxkd
Expected: https://www.screencast.com/t/1F7zyUcxkd
I need javaScript version for looping data in HTML Thanks in advance for helping me..
Upvotes: 0
Views: 101
Reputation: 4592
just for information seek. It will be better to not update the inner HTML so many times. you can do this instead.
document.getElementById("mypanel").innerHTML = dataRequest.map(value => {
return ` Place : ${value.place} <br />
val1 : ${value.countryCode} <br />
val2 : ${value.region} <br />
val3 : ${value.latitude} <br />
val4 : ${value.longitude} <br />
val5 : ${value.distanceMiles} <br />
val6 : ${value.distanceKilometers} <br />
val7 : ${value.directionAngle} <br />
val8 : ${value.directionHeading} <br />`;
}).join("");
Upvotes: 1
Reputation: 5054
Because everytime you are updating the innerHTML with the new text here,
document.getElementById("mypanel").innerHTML = text;
You can do the following,
document.getElementById("mypanel").innerHTML += text;
Upvotes: 1