How To Make A Calculator Using Javascript And Html

How To Make A Calculator Using Javascript And Html

This is a simple Javascript and html web based calculator that that can perform various operations (Addition, Multiplication, Subtraction And Division) .

SOURCE CODE

calculator.html

<html>
	<head>
		<title>Calculator</title>
		<script src = "calculatortest.js"></script>
	</head>
	<body>
		<!-- Field Set -->
		<fieldset style="width:250px">
			<!-- Legend -->
			<legend>Simple Calculator:</legend>
			<!-- HTML Table -->
			<table>
				<tr>
					<!-- First number input field -->
					<td>Number1:</td><td><input type = "number" id = "num1" /></td>
				</tr>
				<tr>
					<!-- Second number input field -->
					<td>Number2:</td><td><input type = "number" id = "num2" /></td>
				</tr>
				<tr>
					<!-- Results input field -->
					<td>Result:</td><td><input type = "text" id = "res" readonly /></td>
				</tr>
			</table>
			<table>
				<tr>
					<!-- Buttons -->
					<td><input type="button" id = "add" value = "+" onclick="operation('+')" /></td>
					<td><input type="button" id = "sub" value = "-" onclick="operation('-')" /></td>
					<td><input type="button" id = "mul" value = "*" onclick="operation('*')" /></td>
					<td><input type="button" id = "div" value = "/" onclick="operation('/')" /></td>
					<td><input type="button" id = "mod" value = "%" onclick="operation('%')" /></td>
				</tr>
			</table>
		</fieldset>
	</body>
</html>

calculatortest.js

operation = (o) => {
  let res = document.getElementById('res');
  let num1 = parseFloat(document.getElementById('num1').value);
  let num2 = parseFloat(document.getElementById('num2').value);
  res.value = calculate(num1, num2, o);
}

calculate = (x, y, o) => {
  if(o == '+') {
    return x + y;
  }
  if(o == '-') {
    return x - y;
  }
  if(o == '*') {
    return x * y;
  }
  if(o == '/') {
    return x / y;
  }
  if(o == '%') {
    return x % y;
  }
}

SCREENSHOTS

ADDITION

SUBTRACTION

MULTIPLICATION

DIVISION

MODULO

VIDEO TUTORIAL

READ MORE  How To Create A New Form In Existing Project In C# Windows Application - Visual Studio 2010

Leave a Reply

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