Basic Calculator
A web staple. This script creates a fully functional calculator using HTML buttons and the JavaScript evaluation engine.
Copy the Script
<script>
function append(val) {
document.getElementById("result").value += val;
}
function solve() {
try {
let x = document.getElementById("result").value;
let y = eval(x);
document.getElementById("result").value = y;
} catch(e) {
document.getElementById("result").value = "Error";
}
}
function clearScreen() {
document.getElementById("result").value = "";
}
</script>
<input type="text" id="result">
<button onclick="append('1')">1</button>
<button onclick="append('+')">+</button>
<button onclick="solve()">=</button>
<button onclick="clearScreen()">C</button>
Frequently Asked Questions
Using `eval()` on user input can be risky if not sanitized, as it can execute arbitrary code. For a simple calculator restricted to numbers and operators, it is generally acceptable, but writing a custom parser is safer.
Yes. You can add a button that calls `Math.sqrt()` on the current display value.
This script relies on clicking the buttons. To support keyboard entry, you would need to add an event listener for `keydown` events.