var result = document.getElementById('result');
var table = document.getElementById('table');
var buttons = table.getElementsByTagName('input');
var operands = ['+', '-', '*', '/'];
for (var index = 0, length = buttons.length; index < length; index++) {
buttons[index].addEventListener('click', onButtonClick, false);
};
// проверяем событие на символ и возвращаем true/false
function isOperand(arr,item) {
var result = false;
for (var index = 0, length = arr.length; index < length; index++) {
if (arr[index] == item) {
return true;
break;
};
};
return result;
};
// вешаем событие на кнопки
function onButtonClick() {
// проверяем на символ =
if (this.value == '=') {
if (isOperand(operands, result.value.substr(-1))) {
alert('Неверный формат данных для вычисления');
return;
};
// проверяем на пустое поле данных
if (!result.value) return false;
// вычисляем результат
if (eval(result.value) !== 'Infinity') {
result.value = eval(result.value);
} else {
alert('Делить на ноль нехорошо. Ай-я-яй!');
result.value = '';
};
return;
};
// кнопка очищения поля ввода
if (this.value == 'C') {
result.value = '';
return;
};
// проверка на пустое поле и нажатии символа
if (isOperand(operands, this.value) && !result.value) return false;
// проверяем на двойной симпол и заменяем на новый
if (isOperand(operands, this.value) && isOperand(operands, result.value.substr(-1))) {
result.value = result.value.substr(0, result.value.length - 1) + this.value;
return;
};
// если все хорошо, то добавляем символ
result.value += this.value;
};
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.