M_66
M_66

Reputation: 299

Dynamically adding collapsible divs by looping through array elements with JavaScript

I am trying to use JavaScript to loop through an array and append collapsible divs to a collapsible set div. I had it working and but not sure what happened. I searched stackoverflow but wasn't able to find an direct answer. I also used the console and I can get each value in the array to appear in the console.

I'm trying to get each day of the week to appear so users can click on the day to see a list of times. Currently, my code causes only monday to appear as a heading that can then be clicked on and expanded. When it is expanded, it shows the rest of the days of the week. I'm guessing that there is something wrong the order of how I'm doing things.

Here is my javascript code:

$(document).on("pagebeforeshow","#ClassTimes",function(){
  $("#classList").empty();
  var collapsibleSet = $("#classList");
  var collapsible = $('<div data-role="collapsible"></div>');
  for (i=0; i<showPrice.length; i++) {
    var maki = showPrice[i].day;
    collapsible.append("<h2>" + maki + "</h2>");
  }
  collapsibleSet.append(collapsible);
  collapsibleSet.trigger('create');
});

With this code, what I currently see is Monday with a plus sign, when I click Monday, it expands and I see the rest of the days of the week. What I want is to have each day of the week as an expandable div.

Here is a link so you can see what I mean. http://mbsk8.zerogravity-web.com/index-x.html#ClassTimes

Upvotes: 1

Views: 1427

Answers (1)

Omar
Omar

Reputation: 31732

You need to create a collapsible inside for or $.each loops. And then append them to collapsible-set and refresh it using .collapsibleset().

var collapsible = '';

$.each(showPrice, function (i, v) {
  collapsible += "<div data-role='collapsible'><h1>" + v.day + "</h1><p>contents</p></div>";
});

$("#classList").append(collapsible).collapsibleset();

Demo

Upvotes: 1

Related Questions