|
| 1 | +"use strict" |
| 2 | +//Selecting the elements |
| 3 | + |
| 4 | +const bill = document.querySelector("#bill"); |
| 5 | +const services = document.querySelector("#services"); |
| 6 | +const people = document.querySelector("#people"); |
| 7 | +const button = document.querySelector("#calc-button"); |
| 8 | +const amount = document.querySelector("#tip-amount"); |
| 9 | +const each = document.querySelector("#each"); |
| 10 | +let total; |
| 11 | + |
| 12 | +//Event listener for the button click |
| 13 | +button.addEventListener("click", calculateTips); |
| 14 | + |
| 15 | +//Function that calculates the tips for each service selection |
| 16 | +function calculateTips() { |
| 17 | + //Checks if some of the fields is blank |
| 18 | + if (bill.value === "" || services.value === "choose-option" || people.value === "") { |
| 19 | + alert("You need to fill in all the fields!"); |
| 20 | + //Changes the tip value for each percentage |
| 21 | + } else { |
| 22 | + switch (services.value) { |
| 23 | + case "outstanding": |
| 24 | + onePerson(); |
| 25 | + total = (bill.value * 0.30) / people.value; |
| 26 | + amount.innerHTML = `€ ${total}`; |
| 27 | + break; |
| 28 | + case "good": |
| 29 | + onePerson(); |
| 30 | + total = (bill.value * 0.20) / people.value; |
| 31 | + amount.innerHTML = `€ ${total}`; |
| 32 | + break; |
| 33 | + case "ok": |
| 34 | + onePerson(); |
| 35 | + total = (bill.value * 0.15) / people.value; |
| 36 | + amount.innerHTML = `€ ${total}`; |
| 37 | + break; |
| 38 | + case "bad": |
| 39 | + onePerson(); |
| 40 | + total = (bill.value * 0.1) / people.value; |
| 41 | + amount.innerHTML = `€ ${total}`; |
| 42 | + break; |
| 43 | + case "terrible": |
| 44 | + onePerson(); |
| 45 | + total = (bill.value * 0.05) / people.value; |
| 46 | + amount.innerHTML = `€ ${total}`; |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +//Function that checks if there is more than one person that pays the bill and adds or deletes the "each" |
| 53 | +function onePerson() { |
| 54 | + if (parseInt(people.value) === 1) { |
| 55 | + each.innerHTML = ""; |
| 56 | + } else { |
| 57 | + each.innerHTML = "each"; |
| 58 | + } |
| 59 | +} |
0 commit comments