0% found this document useful (0 votes)
4 views

Add sub mul div

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Add sub mul div

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Add sub mul div

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Calculator</title>
</head>
<body>
<h2>Simple Calculator</h2>

<!-- Input fields for numbers -->


Number 1: <input type="text" id="num1"><br><br>
Number 2: <input type="text" id="num2"><br><br>

<!-- Buttons for operations -->


<button onclick="calculate('add')">Add</button>
<button onclick="calculate('sub')">Subtract</button>
<button onclick="calculate('mul')">Multiply</button>
<button onclick="calculate('div')">Divide</button>

<script>
function calculate(operation) {
const num1 = parseFloat(document.getElementById("num1").value);
const num2 = parseFloat(document.getElementById("num2").value);

// Check if the inputs are valid numbers


if (isNaN(num1) || isNaN(num2)) {
alert("Please enter valid numbers!");
return;
}

let result;

switch (operation) {
case 'add':
result = num1 + num2;
break;
case 'sub':
result = num1 - num2;
break;
case 'mul':
result = num1 * num2;
break;
case 'div':
result = num2 !== 0 ? num1 / num2 : "Cannot divide by
zero";
break;
}

alert("Result: " + result);


}
</script>
</body>
</html>

You might also like