0
votes

so I'm trying to displays items I get from an API call in a dropdown list. I have the Bootstrap dropdown in a Handlebars file, and am trying to utilize forEach in jQuery to iterate through each item (classroom name) and display them in a dropdown, so a user can select one of the classrooms.

This is the dropdown I have set up in handlebars:

    <div class="btn-group">
      <button type="button" class="btn btn-secondary dropdown-toggle classroom-list-schedule" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Classroom
      </button>
      <div class="dropdown-menu">
        <div class="classroom-dropdown"></div>
      </div>
    </div>

And here are two different things I have tried with jQuery, neither of which have given me quite the result I need:

  const classDropdown = function () {
    data.classrooms.forEach(function (classroom) {
      $('.classroom-dropdown').html('<a class="dropdown-item">' + classroom.classname + '</a>')
    })
  }
  classDropdown()

^ This will only display the last classroom in the dropdown, rather than each. Which does make sense, with the jQuery HTML being inside the forEach function, it's as if it's rewriting each time.

  $('.classroom-dropdown').html(function () {
    data.classrooms.forEach(function (classroom) {
      console.log(classroom.classname)
      return '<a class="dropdown-item">' + classroom.classname + '</a>'
    })
    // return '<a class="dropdown-item">' + 'hi' + '</a>'
  })

^ This one runs the console log, but it seems like the return statement isn't recognized, with no classname being outputted to the drop down, possibly because it's a function inside of a function? But the commented out return does display, which is still an issue because it's outside of the forEach function.

Would anyone be able to point me in the right direction, in terms of which attempt is closer, and what I might be missing?

Thank you!

1

1 Answers

1
votes

Use .append()

Example:

$('.classroom-dropdown').append('<a class="dropdown-item">' + classroom.classname + '</a>')

instead of .html()

Documentation