// Get all the keys from document
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', '*', '/', ',', 'x', '÷'];
var decimalAdded = false;
var input = document.querySelector('.screen input');
// Add onclick event to all the keys and perform operations
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function (e) {
// Get the input and button values
var inputVal = input.value;
var btnVal = this.innerHTML;
var btnValEq = this.getAttribute("value");
// Now, just append the key values (btnValue) to the input string and finally use javascript's eval function to get the result
// If clear key is pressed, erase everything
if (btnVal == 'C') {
input.value = '';
decimalAdded = false;
}
// If eval key is pressed, calculate and display the result
else if (btnVal == '=') {
var equation = inputVal;
calc();
decimalAdded = false;
}
// Basic functionality of the calculator is complete. But there are some problems like
// 1. No two operators should be added consecutively.
// 2. The equation shouldn't start from an operator except minus
// 3. not more than 1 decimal should be there in a number
// We'll fix these issues using some simple checks
// indexOf works only in IE9+
else if (operators.indexOf(btnVal) > -1) {
// Operator is clicked
// Get the last character from the equation
var lastChar = inputVal[inputVal.length - 1];
// Only add operator if input is not empty and there is no operator at the last
if (inputVal != '' && operators.indexOf(lastChar) == -1) {
if (btnValEq) insertAtCaret(btnValEq);
else insertAtCaret(btnVal);
}
// Allow minus if the string is empty
else if (inputVal == '' && btnVal...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.