My code is displaying multiple divs with different outputs from an array, but the information that is for show is only displaying the very first entry on all outputs from i of array..
javascript-
$.ajax(settings).done(function (response) {
const box = `
<div class='box'>
<h4>Away Team</h4>
<div ></div><br>
<h4>Country</h4>
<div ></div><br>
<h4>Competition name</h4>
<div ></div><br>
<h4>Federation</h4>
<div ></div><br>
<h4>Home Team</h4>
<div ></div><br>
<h4>Has expired?</h4>
<div ></div><br>
</div>`;
console.dir(response);
console.dir(response.data[1]);
for (var i = 0; i < response.data.length; i ) { console.dir(response.data[i]); }
for (var i = 0; i < response.data.length; i ) {
$('body').append(box);
$(".away_team").text(response.data[i].away_team);
$(".competition_cluster").text(response.data[i].competition_cluster);
$(".competition_name").text(response.data[i].competition_name);
$(".federation").text(response.data[i].federation);
$(".home_team").text(response.data[i].home_team);
$(".is_expired").text(response.data[i].is_expired);
}
});
}
and html-
<body>
<div >
<h1>Football Predictions</h1>
</div>
<h2> More information soon </h2>
<button type="button" onClick="getgames()">Check info</button>
<script src="js/main.js"></script>
</body>
</html>
EDITED. This is the full code, can someone provide a fix?
Point is to display the information of the array that was outputted to console in body of page, but as is, the code is only repeating entries...
CodePudding user response:
As box
is a container element that has elements with these "away_team", ...etc classes, you need to make sure your jQuery selectors are local to that latest box, as otherwise you'll keep selecting them in all boxes. And in that case, those text
setters will apply to the elements in the first box only.
For that to work correctly, you should first get a reference to the box DOM element (or jQuery wrapper of it), and then pass that as second argument of the $
selectors you have in your loop. So, in the loop body do:
var $box = $(box); // Create and get the DOM element
$('body').append($box);
// Smaller scoped selectors:
$(".away_team", $box).text(response.data[i].away_team);
$(".competition_cluster", $box).text(response.data[i].competition_cluster);
$(".competition_name", $box).text(response.data[i].competition_name);
$(".federation", $box).text(response.data[i].federation);
$(".home_team", $box).text(response.data[i].home_team);
$(".is_expired", $box).text(response.data[i].is_expired);