0

I'm working on a JavaScript short program (trampoline hiring), the purpose of the program is to record according to the name of each customer currently on the trampoline and whether they are an adult or a child (status type).

Currently I have addcustomer, displayallcustomer and deletelastcustomer functions, however I am not sure what I have done wrong for the displayCustomerType(statusType) function. This function is for when I press Display Only Child Customers or Display Only Adult Customers, it will only display child or adult from the array list.

Demo on Fiddle

<html>
  <head>
    <meta charset="utf-8" />
    <title>work 2</title>
    <script type="text/javascript">
      //maximum customer on the trampoline is 5
      const MAX_CUSTOMERS = 5;

      //create new Array
      var customerList = new Array();
   
      //add customer
      function addCustomer() {

        //check max customers
        if (customerList.length >= MAX_CUSTOMERS) {
          alert('Sorry, no more than ' + String(MAX_CUSTOMERS) + ' customers are allowed on the trampoline.');
        } else {
          //add new user
          var newIndex = customerList.length;
          customerList[newIndex] = new Object;

          //ask user enter their name
          customerList[newIndex].name = prompt('What is the customer\'s name?');

          //ask user enter their status   
          customerList[newIndex].status = prompt('Are you a Child or an Adult?');

          //check user is child or adult
          while (!(customerList[newIndex].status == 'child' || customerList[newIndex].status == 'adult')) {
            customerList[newIndex].status = (
            prompt('Error Please Enter \'child\' or \'adult\':'));
          }
        }
      }

      //display customers
      function displayAllCustomers() {
        //create message
        var message = '';

        //loop customers
        for (var i = 0; i < customerList.length; i++) {
          //add customer to message
          message += customerList[i].name + ', Status: ' + String(customerList[i].status) + '. \n';
        }

        //check message
        if (message == '') {
          message = 'There are no customer to display!';
        }

        //output message
        alert(message);
      }

      //delete last customer
      function deleteLastCustomer() {
        //check customer list
        if (customerList.length > 0) {
          //delete last customer
          customerList.length--;
          alert('The last customer has been deleted.');
        } else {
          alert('There are no customer to delete!');
        }
      }

      function displayCustomerType(statusType) {
        var message = '';
        for (var i = 0; i < customerList.length; i++) { //loop through customerlist
          message += customerList[i].status + '. ';
        }

        if ((customerList[i].status = 'child') || (customerList[i].status = 'adult')) {
          alert(message);
        }
      }
    </script>
  </head>
  <body>
    <div>
      <button type="button" onclick="addCustomer();">Add Customer</button>
      <br>
      <button type="button" onclick="displayAllCustomers();">Display All Customers</button>
      <br>
      <button type="button" onclick="deleteLastCustomer();">Delete Last Customer</button>
      <br>
      <button type="button" onclick="displayCustomerType('child');">Display Only Child Customers</button>
      <br>
      <button type="button" onclick="displayCustomerType('adult');">Display Only Adult Customers</button>
      <br>
    </div>
  </body>    
</html>

3
  • Thanks chipchocolate Commented Nov 8, 2014 at 0:58
  • No worries! Like to keep things neat :) Commented Nov 8, 2014 at 1:00
  • chipchocolate, do you know what i did wrong? how come the displaycustomertype function does not work? Commented Nov 8, 2014 at 1:04

3 Answers 3

1

Changed your entire code and now it works.

Demo on Fiddle

HTML:

<body>
    <div>
        <label>Name: </label><input type="text" id="name" />
        <br />
        <label>Adult/Child: </label><input type="text" id="status" />
        <br />
        <br />
        <button>Add Customer</button>
        <br />
        <button>Display All Customers</button>
        <br />
        <button>Delete Last Customer</button>
        <br />
        <button id="Child">Display Only Child Customers</button>
        <br />
        <button id="Adult">Display Only Adult Customers</button>
        <br />
    </div>
    <br />
    <br />
    <div id="message"></div>
</body>

JavaScript:

var buttons = document.getElementsByTagName('button');
var m = document.getElementById('message');
var maxCustomers = 5;
var customerList = [];

buttons[0].onclick = function addCustomer() {
    if (customerList.length >= maxCustomers) {
        m.innerHTML = 'Sorry, no more than ' + maxCustomers + ' customers are allowed on the trampoline.';
    } else {
        var n = document.getElementById('name').value;
        var s = document.getElementById('status').value.toLowerCase();
        if (!n && !s) m.innerHTML = 'Please fill the input boxes first!';
        customerList.push({
            name: n,
            status: s.slice(0, 1).replace(s.slice(0, 1), s.slice(0, 1).toUpperCase()) + s.slice(1, s.length)
        });
        m.innerHTML = n + ' has been added to the List.'
    }
};

buttons[1].onclick = function displayAllCustomers() {
    var message = '';
    for (var i = 0; i < customerList.length; i++) {
        message += 'Name: ' + customerList[i].name + ', Adult/Child: ' + customerList[i].status + '. <br />';
    }
    if (message === '') {
        message = 'There are no customer to display!';
    }
    m.innerHTML = message;
};

buttons[2].onclick = function deleteLastCustomer() {
    if (customerList.length > 0) {
        customerList.length--;
        m.innerHTML = 'The last customer has been deleted.';
    } else {
        m.innerHTML = 'There are no customer to delete!';
    }
};

buttons[3].onclick = buttons[4].onclick = function displayCustomerType() {
    var message = '';
    for (var i = 0; i < customerList.length; i++) {
        if (customerList[i].status == this.id) {
            message += 'Name: ' + customerList[i].name + ', Adult/Child: ' + customerList[i].status + '. <br />';
        }
    }
    if (message === '') {
        message += 'None Found!';
    }
    m.innerHTML = message;
};
Sign up to request clarification or add additional context in comments.

1 Comment

First I thought, "Great. Someone gave the OP copy-and-paste code to use." Then I read your answer. Excellent work. +1. Whereas I tried to use English to hopefully impart something useful, you had the brilliant idea to write a real implementation of the question's underlying functionality. If the OP manages to make any sense of this, it will be a learning experience, and I learned something about how to help people help themselves. Thank you.
1

There are two points here.

  1. You should use good function names.
  2. You must understand what you want your code to do.

1. Use good function names.

Your function is named displayCustomerType(). It accepts one argument. If I was to guess the purpose of the displayCustomerType(arg) function does, I would suppose that it displays the type of a customer object which is provided as an argument. Therefore, if I provided it with a customer of the "child" type, I might expect it to display the type "child."

If I'm correct, this is not what you want to happen. Your button is named "Display All Child Customers." Therefore, I assume that you would prefer to provide the function with a customer type and then display all customers from your list of customers which have that type.

Addressing this problem is simple. Use good function names. displayCustomersOfType(arg) would do. Using a function name like that would make it clearer to people who are using your code that your code functions in a certain way.

2. Understand what you want your code to do.

Maybe you think you know what you want your code to do. You have it in your head. You asked in a comment, "Why is it showing 'child, child, child'?" I'll tell you why. It's displaying that because that's what you told it to display. Let's break down what this displayCustomersOfType(arg) function should do.

  1. Accept an argument.
  2. Use the argument to filter the number of customers being displayed.
  3. Display all of the customers which pass the filter.

Then we can start thinking about how this should work in code. We have an array of customer objects. Each one has a status and a name among other things. You want to call on this function, provide it with an customer type argument, filter the list of customers with that argument, and display the customers which pass the filter. Let's start figuring out how that can be coded.

  1. Create a function displayCustomersOfType(arg)
  2. For each customer in the list of customers,
  3. If the customer's type is equal to the specified type,
  4. Append that customer's name to the output.
  5. Display the output.

Each of these is a logical step in the process. Being able to interpret abstract requirements like the first set of steps and understand them in terms of logical steps like the second set of steps is an absolutely vital skill for a software developer. I suspect that you want to become a software developer because you have software development homework. If I'm correct, then you need to develop this skill.

Let's look at an example.

I have some fruit. There are two apples, a banana, and two cherries. I want to write a function which will only show those fruits that have a particular name. For each fruit in my list of fruits, I'll add the fruit to the message if it has the name that I specify. Then I'll display the list of fruit with that name.

JSFiddle: http://jsfiddle.net/kLur4qc5/

var fruits = ['apple', 'apple', 'banana', 'cherry', 'cherry'],
    showFruitsWithName = function (name) {
        var message = "";
        fruits.forEach(function (fruit) {
            if (fruit === name) {
                message += name + " ";
            }
        });
        alert(message);
    };

showFruitsWithName('cherry');

There is an answer here. It's written in the five step list. I even bolded some keywords for you. I have faith that you can make sense of the example code and apply it to your purpose. You can figure this out.

Ask questions. I'll answer them, but try to make them specific questions. Don't ask "How do I do this? Please provide complete code examples that I can copy and paste." I know that it's tempting to do that especially since you get answers pretty quickly that way, but you're only hurting yourself if you don't truly understand this stuff.

Comments

0

Your curly brackets are a little off scope. It should be more like:

var message = '';
for (var i = 0; i < customerList.length; i++) {
    if (customerList[i].status === statusType) message += customerList[i].status + '. ' ;
}
alert(message);

6 Comments

ok thanks, how come when i test it(click the Display Only Child Customers button), it only shows 'child, child, child'?
@Jessie: Look at the code. It says, "For each customer, loop. If the status is equal to this status type, add that status to the end of the message." Think about what you want. You want to say "Bill, John, Jane"? You need to create a message that has the names of the customers and not the status.
my approach is to look through customer list array, and then use if to check if the .status of that element is either parent or child. but i don't know what i did wrong?
You appended the status to the message. That's why you ended up with "child, child, child."
i thought we need to check it whether if its 'child' or 'adult' so then we alert the message? sorry Iv just learned javascript
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.