Calculator

Why? Practice event handling, math operations, and DOM updates.

<!DOCTYPE html>
<html>
<head>
  <title>Calculator</title>
  <style>
input { width: 200px; padding: 10px; margin: 5px; }
button { padding: 10px; margin: 2px; }
</style> </head> <body> <h2>Simple Calculator</h2> <input type="text" id="display" disabled> <br> <button onclick="press('1')">1</button> <button onclick="press('2')">2</button> <button onclick="press('3')">3</button> <button onclick="press('+')">+</button> <br> <button onclick="press('4')">4</button> <button onclick="press('5')">5</button> <button onclick="press('6')">6</button> <button onclick="press('-')">-</button> <br> <button onclick="press('7')">7</button> <button onclick="press('8')">8</button> <button onclick="press('9')">9</button> <button onclick="press('*')">*</button> <br> <button onclick="press('0')">0</button> <button onclick="press('/')">/</button> <button onclick="calculate()">=</button> <button onclick="clearDisplay()">C</button> <script>
function press(value) {
  document.getElementById("display").value += value;
}
function calculate() {
  let exp = document.getElementById("display").value;
  document.getElementById("display").value = eval(exp);
}
function clearDisplay() {
  document.getElementById("display").value = "";
}
</script> </body> </html>

Explanation:

  • Buttons call press() to append numbers/operators.
  • calculate() uses eval() to evaluate expression.
  • clearDisplay() clears input.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *