Monday, 26 August 2013

Hello guys, I need a little help here

Hello guys, I need a little help here

Hello guys I'm currently working on a calculator function using JavaScript
and I wonder why this one doesn't get the values whenever I click a number
or an operator.
I just found this code snippet on the internet and I tried it on mine and
i don't know why it didn't work.
You can try and run my code. Here is my HTML:
<div id="calculator">
<div class="top">
<span class="clear">C</span>
<div class="screen"></div>
</div>
<div class="keys">
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">+</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span class="operator">-</span>
<span>1</span>
<span>2</span>
<span>3</span>
<span class="operator">÷</span>
<span>0</span>
<span>.</span>
<span class="eval">=</span>
<span class="operator">x</span>
</div></div>
Here is my JavaScript:
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;
for(var i = 0; i < keys.length; i++) {
keys[i].onclick = function(e) {
var input = document.querySelector('.screen');
var inputVal = input.innerHTML;
var btnVal = this.innerHTML;
if(btnVal == 'C') {
input.innerHTML = '';
decimalAdded = false;
}
else if(btnVal == '=') {
var equation = inputVal;
var lastChar = equation[equation.length - 1];
equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
if(operators.indexOf(lastChar) > -1 || lastChar == '.')
equation = equation.replace(/.$/, '');
if(equation)
input.innerHTML = eval(equation);
decimalAdded = false;
}
else if(operators.indexOf(btnVal) > -1) {
var lastChar = inputVal[inputVal.length - 1];
if(inputVal != '' && operators.indexOf(lastChar) == -1)
input.innerHTML += btnVal;
else if(inputVal == '' && btnVal == '-')
input.innerHTML += btnVal;
if(operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
input.innerHTML = inputVal.replace(/.$/, btnVal);
}
decimalAdded =false;
}
else if(btnVal == '.') {
if(!decimalAdded) {
input.innerHTML += btnVal;
decimalAdded = true;
}
}
else {
input.innerHTML += btnVal;
}
e.preventDefault();
}
}
I hope you can help me out with this one guys thank you so much :)

No comments:

Post a Comment