EXam Javascript+JSON

This is a simple example that shows how to process an array of JSON objects.

by Ken Wai Ooi

HTML

<!-- division for the report -->
<div id="report"></div>


<select id="petType" >
   <option>fish</option>
   <option>dog</option>
   <option>cat</option>
</select>
<button onclick="generateReport()">Submit</button>

CSS

#report {
  width: 250px;
  height: 100px;
  background-color: lightyellow;
}

JavaScript

// Here is inventory on the car lot
var pet = [
{type: "fish", breed: "guppy"},
{type: "fish", breed: "goldfish"},
{type: "dog",	breed: "labrador"},
{type: "cat",	breed: "tabby"},
{type: "dog",	breed: "beagle"},

];

// Count how many cars there are of a certain colour and make
function howMany(petType) {
   var count = 0;
   for (var i=0 ; i<pet.length ; i++) {
      if (pet[i].type == petType) {
         count++;
      }
   }
   return count;
}

// Generate a report showing the
// nubmer of cars with a given colour and make combination
function generateReport() {
   var thepetType = document.getElementById("petType").value;
   var theCount = howMany(thepetType);
   var verb = "are";
   var plural = "s";
   
   if (theCount == 1) {
       verb = "is";
       plural = "";
   }
   
   var htmlText = "<p> There " + verb + " " + theCount + " " + thepetType + plural;
   document.getElementById("report").innerHTML = htmlText;
}