Dexstrum Dexstrum - 7 months ago 139
Javascript Question

Populate UL with JSON

I am trying to populate a UL list in a bootstrap dropdown menu with JSON. Here is the bootstrap menu:

<section class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Select A State
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
</ul>
</section>


Here is the JSON:

//Create json list of dropdown
var jsonList = {"List" : [
{"id" : "al", "Name" : "AL"},
{"id" : "ak", "Name" : "AK"},
{"id" : "az", "Name" : "AZ"}
]}

//Populate dropdown menu for selection of dropdown
$(document).ready(function(){
var listItems = "";
for (var i = 0; i < jsonList.List.length; i++){
listItems += "<li><a href='#'>" + jsonList.List[i].id + "'>" + jsonList.List[i].Name + "</a></li>";
}
$("#dropdown-menu").append(listItems);
});


I don't know if I am not setting my references right, or if I am not using correct syntax.

Answer

There was a malformed anchor tag:

listItems += "<li><a href='url/to/" + jsonList.List[i].id + "'>" + jsonList.List[i].Name + "</a></li>"; (removed double closing angled bracket)

Also the dropdown selector was a class selector

$(".dropdown-menu").html(listItems);

Comments