Eight Eight - 4 months ago 18
HTML Question

Bootstrap dropdown generated with javascript

By using getelementbyID and a for loop I was hoping to be able to create a dropdown button and automatically fill it with entries from an array. Unfortunately it doesn't seem to be working as the html for the dropdown closes itself before I tell it to.

This is my code

var contacts = [
"John",
"John",
"John",
"John",
"John",
"John",
"John",
];
function phone() {
document.getElementById("optionscontainer").innerHTML = document.getElementById("optionscontainer").innerHTML + '<span class="dropdown"><a href="#" class="dropdown-toggle btn btn-default" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Phone <span class="caret"></span></a><ul class="dropdown-menu">';
for (i = 0; i < contacts.length; i++) {
document.getElementById("optionscontainer").innerHTML = document.getElementById("optionscontainer").innerHTML + '<li><a onclick="call(' + i + ')" href="#">' + contacts[i] + '</a></li>';
if (i == contacts.length) {}
}
document.getElementById("optionscontainer").innerHTML = document.getElementById("optionscontainer").innerHTML + '</ul></span>';
}


As you see I open the dropdown before the loop, then I use the loop to list all the options that should be inside it, and at the end I close it.

Once I run it though, I just get a broken dropdown (example can be seen here http://creativiii.com/test/test.html). After inspecting the html with chrome I noticed that, for some reason,
</ul></span>
are written right before the loop starts instead that at the end where I want them, breaking the dropdown completely.

How can I fix this? In the link I provided I also posted an example of how the dropdown should look.

Answer

The problem here happens when you're modifying the uncomplete html, browser corrects it as it thinks it's right, so you end up with menu out of the parent. That's where temporary variable for holding elements before insertion steps in like in example down .

var contacts = [
  "John",
  "John",
  "John",
  "John",
  "John",
  "John",
  "John",
];

function phone() {
  var menuHtml = '<span class="dropdown"><a href="#" class="dropdown-toggle btn btn-default" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Phone <span class="caret"></span></a><ul class="dropdown-menu">';
  for (i = 0; i < contacts.length; i++) {
    menuHtml += '<li><a onclick="call(' + i + ')" href="#">' + contacts[i] + '</a></li>';
  }
  menuHtml += '</ul></span>';
  document.getElementById("optionscontainer").innerHTML = menuHtml;
}

phone();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="optionscontainer"></div>