Share
Explore

The JavaScript Calculator

Extend the previous application code to make a calculator: the front end html has fields for 2 input numbers and the operations add, subtract, multiple, divide, and a field for the output. The back end server does the work, takes the input and sends back the result. Use CSS to make it look like a day at the Caribbean beach.
To extend the previous application code to create a calculator with a front-end HTML form for two input numbers and the operations add, subtract, multiply, divide, and a field for the output, follow these steps:
Set up the backend (app.js):
Update the backend to handle the calculation requests.
Create a public directory with HTML, CSS, and JavaScript files:
index.html: Main HTML file.
styles.css: CSS file for styling.
script.js: JavaScript file for handling interactions.
Here is the complete implementation:
Step 1: Backend (app.js)
javascript
Copy code
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// Middleware to serve static files and parse URL-encoded data from the form
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

// Route to handle calculation
app.post('/calculate', (req, res) => {
const { num1, num2, operation } = req.body;
let result;

const number1 = parseFloat(num1);
const number2 = parseFloat(num2);

switch (operation) {
case 'add':
result = number1 + number2;
break;
case 'subtract':
result = number1 - number2;
break;
case 'multiply':
result = number1 * number2;
break;
case 'divide':
result = number1 / number2;
break;
default:
result = 'Invalid operation';
}

res.json({ result });
});

app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});

Step 2: Frontend (public/index.html)
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Caribbean Beach Calculator</h1>
<div class="calculator">
<input type="number" id="num1" placeholder="Enter first number">
<select id="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="number" id="num2" placeholder="Enter second number">
<button id="calculateButton">Calculate</button>
<p id="result"></p>
</div>
<script src="script.js"></script>
</body>
</html>

Step 3: CSS (public/styles.css)
css
Copy code
body {
font-family: Arial, sans-serif;
background-image: url('https://example.com/caribbean-beach.jpg'); /* Replace with a URL to a beach image */
background-size: cover;
color: #fff;
text-align: center;
padding: 50px;
}

h1 {
margin-bottom: 20px;
}

.calculator {
background: rgba(0, 0, 0, 0.5);
padding: 20px;
border-radius: 10px;
display: inline-block;
}

input, select, button {
margin: 10px 0;
padding: 10px;
font-size: 16px;
border: none;
border-radius: 5px;
}

button {
background-color: #4CAF50;
color: white;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}

p#result {
font-size: 20px;
margin-top: 20px;
}

Step 4: JavaScript (public/script.js)
javascript
Copy code
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('calculateButton').addEventListener('click', () => {
const num1 = document.getElementById('num1').value;
const num2 = document.getElementById('num2').value;
const operation = document.getElementById('operation').value;

fetch('/calculate', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
num1,
num2,
operation
})
})
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = `Result: ${data.result}`;
});
});
});

Running the application:
Save the above files in their respective locations.
Ensure you have a public directory with the files index.html, styles.css, and script.js.
Start the Node.js server:
bash
Copy code
node app.js

Open your web browser and navigate to http://localhost:3000.
Explanation:
The backend (app.js) handles the calculation logic and serves static files.
The HTML file (index.html) provides a form with fields for two input numbers and a selection for the operation, along with a button to submit the form.
The CSS file (styles.css) styles the page to look like a day at the Caribbean beach.
The JavaScript file (script.js) handles the form submission, sends the data to the server, and updates the result on the page.
New version of GPT available - Continue chatting to use the old version, or start a
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.