Calculator Coding In Html

HTML

12/27/20232 min read

simple calculator code
simple calculator code

Basic Calculator Code In HTML CSS and Javascript

Here's a simple HTML code for a basic calculator

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Simple Calculator</title>

<style>

input {

width: 100%;

padding: 10px;

margin: 5px 0;

}

</style>

</head>

<body>

<h2>Simple Calculator</h2>

<form name="calculator">

<input type="text" name="display" id="display" readonly>

<br>

<input type="button" value="1" onclick="appendToDisplay('1')">

<input type="button" value="2" onclick="appendToDisplay('2')">

<input type="button" value="3" onclick="appendToDisplay('3')">

<input type="button" value="/" onclick="appendToDisplay('/')">

<br>

<input type="button" value="4" onclick="appendToDisplay('4')">

<input type="button" value="5" onclick="appendToDisplay('5')">

<input type="button" value="6" onclick="appendToDisplay('6')">

<input type="button" value="-" onclick="appendToDisplay('-')">

<br>

<input type="button" value="7" onclick="appendToDisplay('7')">

<input type="button" value="8" onclick="appendToDisplay('8')">

<input type="button" value="9" onclick="appendToDisplay('9')">

<input type="button" value="+" onclick="appendToDisplay('+')">

<br>

<input type="button" value="0" onclick="appendToDisplay('0')">

<input type="button" value="." onclick="appendToDisplay('.')">

<input type="button" value="C" onclick="clearDisplay()">

<input type="button" value="=" onclick="calculate()">

</form>

<script>

function appendToDisplay(value) {

document.calculator.display.value += value;

}

function clearDisplay() {

document.calculator.display.value = "";

}

function calculate() {

try {

document.calculator.display.value = eval(document.calculator.display.value);

} catch (error) {

document.calculator.display.value = "Error";

}

}

</script>

</body>

</html>

This code creates a basic calculator with buttons for digits, arithmetic operations, and a display for the results. Keep in mind that using eval for calculations can have security implications in a real-world application, so be cautious if you plan to extend this for production use.

Related Stories