Matthew Matthew - 3 months ago 9
jQuery Question

Applying Names / Values to HTML List from Javascript Array of Objects

I have a Javascript array of objects populating an HTML list.

<html>
<head>
<script src="jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
// js array of objects
var location = [{
City: "Akron",
State: "Ohio",
Temperature_1: 50,
Temperature_2: 65
}, {
City: "Charlotte",
State: "North Carolina",
Temperature_1: 80,
Temperature_2: 90
}];

// populate webpage with locations and temperatures
$.each(location, function(key, val) {
var $locationList = $("<li>" + "<div class='group'>" + val.City + "<div class='both_temperatures '>" + "<div class='temperature'>" + val.Temperature_1 + "</div>" + "<div class='temperature'>" + val.Temperature_2 + "</div></div><div class='state'>" + val.State + "</div></li>");
$("#locationList").append($locationList);
});
});
</script>
</head>
<body>
<ul id="locationList"></ul>
</body>
</html>


I'm able to get the following output:

<ul id="locationList">
<li>
<div class="group">Akron
<div class="both_temperatures">
<div class="temperature">50</div>
<div class="temperature">65</div>
</div>
<div class="state">Ohio</div>
</div>
</li>
<li>
<div class="group">Charlotte
<div class="both_temperatures">
<div class="temperature">80</div>
<div class="temperature">90</div>
</div>
<div class="state">North Carolina</div>
</div>
</li>
</ul>


How do I assign names within the "class" divs and values within the "temperature" divs?

Here is my desired output:

<ul id="locationList">
<li>
<div class="group" name="Akron">Akron
<div class="both_temperatures">
<div class="temperature" value="50">50</div>
<div class="temperature" value="65">65</div>
</div>
<div class="state" name="Ohio">Ohio</div>
</div>
</li>
<li>
<div class="group" name="Charlotte">Charlotte
<div class="both_temperatures">
<div class="temperature" value="80">80</div>
<div class="temperature" value="90">90</div>
</div>
<div class="state" name="North Carolina">North Carolina</div>
</div>
</li>
</ul>

Answer

try this

var $locationList = $("<li>" + "<div class='group' name='"+val.City+"'>" + val.City + "<div class='both_temperatures '>" + "<div class='temperature' value='"+val.Temperature_1+"'>" + val.Temperature_1 + "</div>" + "<div class='temperature' value='"+val.Temperature_2+"'>" + val.Temperature_2 + "</div></div><div class='state' name='"+val.State+"'>" + val.State + "</div></li>");