0

I have a section on my website to hold a drop-down list. I filled the list with objects from an API call.

When I try to create buttons based on each country in the list, it appends "Denmark" regardless of which country is selected in an h1 tag format.

JQuery:

for (var i=0; i< results.length; i++){
            //console.log(results[i].country);
            var countryList = $("#your-team");
            var newList = $("<li><a class='dropdown-item teamselect' id = '" + results[i].fifa_code + "' href='#follow-teams'>"+ results[i].country + "</a></li>");

            countryList.append(newList);

            var fifaCode = results[i].fifa_code;
            var fifaCodePound = "#" + fifaCode;
            console.log(fifaCodePound);
            var teamInfo = $("#teaminfo");
            var teamTitle = $("#teampagetitle");
            var teamStat = $(
                "<h1>" + results[i].country + "</h1> <span> Wins: " + results[i].wins 
                + "</span><br><span> Losses:" + results[i].losses + "</span>"
            );

            $(newList).on("click", function(event) {
                    //teamTitle.append("<h1>" + results[i].country + "</h1>");
                    teamInfo.append(teamStat);
                    $("#placeholder").style("height: auto;")

HTML

<section id = "follow-teams">
            <div class="container">
                <div class= "row">

                    <div class="dropdown">
                        <h1>Follow your favorite teams</h1>
                        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select a Team to Follow
                        <span class="caret"></span></button>
                        <div id="your-team" class="dropdown-menu team-dropdown">
                            <!-- <li id="your-team"></li> -->
                        </div>

                        <div id = "teaminfo"></div>
                    </div>
                </div>
                <br>
                    <div class="row">
                        <div class="team-buttons"></div>
                    </div>
Community
  • 1
  • 1
Samuel
  • 1
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Taplar Jul 05 '18 at 22:03
  • `var` variables are method level variables. Each time your loop iterates, it will replace any var element that it has. As such, the `teamStat` variable you have is being shared by all the event handlers and will be the last iteration of the loop. – Taplar Jul 05 '18 at 22:04
  • That makes so much sense, I checked the API again and low and behold the last object for country was Denmark. Thanks for the reply, much appreciated! :) – Samuel Jul 05 '18 at 22:46

0 Answers0