Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active October 14, 2021 19:09
Show Gist options
  • Save acidtone/fb9d28505944280f548ad6dde0890102 to your computer and use it in GitHub Desktop.
Save acidtone/fb9d28505944280f548ad6dde0890102 to your computer and use it in GitHub Desktop.
JS Activity: Refactor Adding Machine to create Simple Calculator

JS Activity: Refactor Adding Machine to create Simple Calculator

in this activity, you will refactor a simple adding machine to create a siimple calculator that also subtracts, multiplies and divides two numbers based on a select menu.

Instructions

  1. Add a select menu to the form in index.html that has the following options:
    • Add
      • value: add
    • Subtract
      • value: subtract
    • Multiply
      • value: multiply
    • Divide
      • value: divide
  2. Using conditional statements, perform the correct operation on the two numbers based on the menu option selected.
  3. Output the result to the page using an output element.
// Create a variable for the form
const form = document.querySelector('form');
const handleSubmit = function(event) {
// Stop form from submitting and refreshing the page
event.preventDefault();
// Assign operands
const num1 = Number(form.first.value);
const num2 = Number(form.second.value);
// Calculate total
const total = num1 + num2;
// Print total to page
form.total.value = total;
// console.log(event);
}
form.addEventListener('submit', handleSubmit);
// console.log(form);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<script src="calculator.js" defer></script>
<style>
input, label {
display: block;
}
</style>
</head>
<body>
<h1>Calculator</h1>
<form action="">
<legend>Enter two numbers to add:</legend>
<fieldset>
<label for="first">First Number</label>
<input type="number" id="first" name="first" required>
<label for="second">Second Number</label>
<input type="number" id="second" name="second" required>
<input type="submit" value="Add numbers">
<h2>Total: <output id="total"></output></h2>
</fieldset>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment