Tip Calculator

Project Description

Calculates the tip for a restaurant bill based on the level of service and the number of customers.

You can view a completed version of the project here.

Your project folder

In your portfolio/js folder is a folder named tip-calculator that contains all the files you need for this JavaScript project.

In VS Code, open the project’s index.html web page and ensure the hyperlinks and personal details have been correctly updated.

Adding the JavaScript code

Follow the steps below to add the JavaScript code to the index.html file.

  1. Scroll down the web page until you see an empty pair of opening <script> and closing </script> tags.
  2. Click inside the empty pair of tags and paste the JavaScript code below.
    //Hide the tip amount on load
    document.getElementById("tipDisplayBox").style.display = "none";
    document.getElementById("numOfPeople").value = 1;
    
    // Calculate tip
    function calculateTip() {
       let billAmount = document.getElementById("billAmount").value;
       let serviceQuality = document.getElementById("serviceQuality").value;
       let numOfPeople = document.getElementById("numOfPeople").value;
    
       // Validate input
        if (billAmount === "" || serviceQuality == 0) {
          alert("Please enter values");
          return;
       }
    
       // Calculate tip
       let tipTotal = (billAmount * serviceQuality);
       // round to two decimal places
       tipTotal = Math.round(tipTotal * 100) / 100;
       // next line allows us to always have two digits after decimal point
       tipTotal = tipTotal.toFixed(2);
       // Display the tip
       document.getElementById("tipDisplayBox").style.display = "block";
       document.getElementById("tipTotal").innerHTML = tipTotal;
       // Check to see if this input is empty or less than or equal to 1
       if (numOfPeople === "" || parseInt(numOfPeople) <= 1)  {
          numOfPeople = 1;
          document.getElementById("numOfPeople").value = 1;
          tipEach = tipTotal;
       }
      document.getElementById("tipEach").innerHTML = (tipTotal / numOfPeople).toFixed(2);
    }
    
    // click to call function
    document.getElementById("calculate").onclick = () => calculateTip();
  3. Save your index.html file.
  4. Display the file in a web browser and verify it works correctly.

Save your file and verify it works correctly.

Uploading your project to GitHub

Upload the tip-calculator folder as a sub-folder of the portfolio/js folder on your GitHub account.