1

I'm a little stuck on my javascript homework. Here are the requirements

  1. Create a new JavaScript file. Inside this file create a constructor that creates animal objects. An animal object should store the following properties:

    • Name – the name of the animal
    • Gender – the gender of the animal
    • Species – the species of the animal
  2. Create a global array that will store an unknown number of animal objects.

  3. Create an addAnimal() functions that runs when the Add Animal button is clicked. This function should do the following things:

    • Determine the name, gender, and species of the animal from the user input fields
    • Create an animal object from the user information
    • Push the animal object onto the array
    • Update the output/display
  4. Create a function that will display all of the animals stored in the array as an unordered list on the page.

here's what I have written in html doc so far. Ive been struggling with this and I'm not sure how to implement the constructor function properly:

<!DOCTYPE HTML 5.13.14>
<html>
    <head>
    <link type="text/css" rel="stylesheet" 
      href="ex12.js">
    <title> Alleluia CPSC 1045 Exersize 12         </title>

     <script>

     function addAnimal(name, type, gender) {
        this.name = name,
        this.type = type,
        this.gender = gender,
        this.result = function addAnimal() {

            onclick return this.name +   this.type + this.gender;
        }
    }

       </script>
      </head>

      <body>
      <h1> Welcome to the CPSC 1045 Zoo!</h1>
      <br>
      <p> Please add an animal to the zoo by  filling out the following feilds</p>
      <br>
      <p> Animal Name: <input type="text"     id="name" name="inputname"></p>
      <p> Animal Type: <input type="text"    id="type" name="inputtype"></p>

     <!--- radio input --->
     <p> Animal Gender: 
        <input type="radio" name="gender"      value="Male" id="genderm"> Male
         <input type="radio" name="gender"   value="Female" id="genderf"> Female
       </p> 
      <!--- end--->

      <button type="button"     onclick='addAnimal()' id="result"><b>Add      Animal</b></button>

</body>
</html>
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47

2 Answers2

1
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <!-- from the user input fields -->
    <fieldset>
        <legend>Animal</legend>
        <div>
            <label for="name">Name: </label>
            <input type="text" id="name">
        </div>
        <div>
            <label>Gender</label>
            <input type="radio" id="male" name="gender" value="Male">
            <label for="kraken">Male</label>
            <input type="radio" id="female" name="gender" value="Female">
            <label for="female">Female</label><br />

        </div>
        <div>
            <label for="species">Species: </label>
            <input type="text" id="species">
        </div>

        <button onclick="addAnimal()"> Add Animal</button>
    </fieldset>


    <hr>
    <hr>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Gender</th>
                <th>Species</th>
            </tr>
        </thead>

        <tbody id="animal-list">

        </tbody>
    </table>

    <script>
        //Create a global array that will store an unknown number of animal objects.
        var animalStore = [];
        // Create a new JavaScript file. Inside this file create a constructor that creates animal objects. An animal object should store the following properties:
        // Name – the name of the animal
        // Gender – the gender of the animal
        // Species – the species of the animal
        function Animal(name, gender, species) {
            this.name = name;
            this.gender = gender;
            this.species = species;
        }

        // Create an animal object from the user information
        //Create an addAnimal() functions that runs when the Add Animal button is clicked. This function should do the following things:
        function addAnimal() {
            let name = document.getElementById('name').value;
            let gender = Array.from(document.getElementsByName('gender')).filter(o => o.checked)[0].value;
            let species = document.getElementById('species').value;
            let animalInstance = new Animal(name, gender, species);
            animalStore.push(animalInstance);
            displayAnimalList();
            resetInputFields();       // reset the input fields after submit
        }

        //Create a function that will display all of the animals stored in the array as an unordered list on the page.
        function displayAnimalList() {
            let template = '';
            for (let index = 0; index < animalStore.length; index++) {
                const animal = animalStore[index];
                template += `<tr><td>${animal.name}</td><td>${animal.gender}</td><td>${animal.species}</td></tr>`;
            }
            document.getElementById("animal-list").innerHTML = template;        // you can optimize it to not render whole list again and again- only newly animal added 
        }

        function resetInputFields() {
            document.getElementById('name').value = "";
            Array.from(document.getElementsByName('gender')).map(o => o.checked = false);
            document.getElementById('species').value = "";
        }
    </script>


</body>

</html>
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
1

Create a new JavaScript file. Inside this file create a constructor that creates animal objects. An animal object should store the following properties:

  • Name – the name of the animal
  • Gender – the gender of the animal
  • Species – the species of the animal
 animals.push({
  id: animals.length + 1,
  name: animal_name.value,
  gender: animal_gender.value,
  species: animal_species.value
});

Create a global array that will store an unknown number of animal objects.

let animals = [];

Create an addAnimal() functions that runs when the Add Animal button is clicked. This function should do the following things:

  • Determine the name, gender, and species of the animal from the user input fields
  • Create an animal object from the user information
  • Push the animal object onto the array
  • Update the output/display
function addAnimal() {
  var animal_name = document.getElementById('name');
  var animal_gender = document.getElementById('gender');
  var animal_species = document.getElementById('species');

    animals.push({
      id: animals.length + 1,
      name: animal_name.value,
      gender: animal_gender.value,
      species: animal_species.value
    });
  }

Create a function that will display all of the animals stored in the array as an unordered list on the page.

function updateDisplay(identifier) { 
    var animal = animals.find(obj => {
      return obj.id === identifier
    }); 
  var table = document.getElementById('animals').getElementsByTagName('tbody')[0];
    var newRow = table.insertRow();
  //Col 1
  var newCell = newRow.insertCell(0);
  var newText = document.createTextNode(animal.name);
  newCell.appendChild(newText);
  //Col 2
  newCell = newRow.insertCell(1);
  var newText = document.createTextNode(animal.gender);
  newCell.appendChild(newText);
  //Col 3
  newCell = newRow.insertCell(2);
  var newText = document.createTextNode(animal.species);
  newCell.appendChild(newText);
}

Error Handling is not covered in the requirements, but is useful for verifying the data you want to add to the array actually exists. As per:

function handleErrors(name, gender, species) {
  var error = document.getElementById('error');
  var errorText = "";

  if (name == null || name.value == '') {
    errorText += "Name cannot be blank. ";
  }

  if (gender == null || gender.value == '') {
    errorText += "Gender cannot be blank. ";
  }

  if (species == null || species.value == '') {
    errorText += "Species cannot be blank. ";
  }

  if (errorText != "") {
    error.classList.remove("hidden");
    error.innerText = errorText;
    return true;
  } else {
    return false;
  }
}

Please note too, the difference between this example and the other varies, but this one offers:

  • Adding items to an array after data validation
  • Adding rows to a table using the built in Javascript functions insertCell, insertRow and createTextNode

See the full example:

let animals = [];

function updateDisplay(identifier) { 
 var animal = animals.find(obj => {
      return obj.id === identifier
    }); 
  var table = document.getElementById('animals').getElementsByTagName('tbody')[0];
 var newRow = table.insertRow();
  //Col 1
  var newCell = newRow.insertCell(0);
  var newText = document.createTextNode(animal.name);
  newCell.appendChild(newText);
  //Col 2
  newCell = newRow.insertCell(1);
  var newText = document.createTextNode(animal.gender);
  newCell.appendChild(newText);
  //Col 3
  newCell = newRow.insertCell(2);
  var newText = document.createTextNode(animal.species);
  newCell.appendChild(newText);
}

function addAnimal() {
  var animal_name = document.getElementById('name');
  var animal_gender = document.getElementById('gender');
  var animal_species = document.getElementById('species');

  if (!handleErrors(animal_name, animal_gender, animal_species)) {
    animals.push({
      id: animals.length + 1,
      name: animal_name.value,
      gender: animal_gender.value,
      species: animal_species.value
    });
    updateDisplay(animals.length);
  }
}

function handleErrors(name, gender, species) {
  var error = document.getElementById('error');
  var errorText = "";

  if (name == null || name.value == '') {
    errorText += "Name cannot be blank. ";
  }

  if (gender == null || gender.value == '') {
    errorText += "Gender cannot be blank. ";
  }

  if (species == null || species.value == '') {
    errorText += "Species cannot be blank. ";
  }

  if (errorText != "") {
    error.classList.remove("hidden");
    error.innerText = errorText;
    return true;
  } else {
    error.classList.add("hidden");
    error.innerText = "";
    return false;
  }
}
.wrapper {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  margin-left: auto;
  margin-right: auto;
  background-color: lightgray;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  padding: 35px;
}

.wrapper * {
  margin: 5px;
  padding: 5px;
}

.wrapper button {
  height: 40px;
  opacity: 0.8;
}

.wrapper button:hover {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  opacity: 1;
}

.hidden {
  display: none;
}

.error {
  color: darkred;
  text-align: center;
}

table {
  max-width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding: 35px;  
}

table th {
  width: 23vw;
  background-color: lightgray;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

table tr {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  }
  
table tr:nth-child(even) {
  background-color: #f2f2f2;
  }
<div class="wrapper">
  <input type="text" id="name" placeholder="Animal Name" />
  <input type="text" id="gender" placeholder="Animal Gender" />
  <input type="text" id="species" placeholder="Animal Species" />
  <button type="button" onclick="addAnimal()">Add Animal</button>
  <label id="error" class="hidden error"></label>
</div>

<table id="animals">
  <thead>
    <tr>
      <th> Name </th>
      <th> Gender </th>
      <th> Species </th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Please also see these for reference:

EGC
  • 1,719
  • 1
  • 9
  • 20