[SRC] [javascript] Calculadora básica estilo Windows

Iniciado por Psyke1, 16 Octubre 2012, 11:42 AM

0 Miembros y 1 Visitante están viendo este tema.

Psyke1

Código (javascript) [Seleccionar]
Sí, lo sé, las calculadoras están muy vistas, pero como lo tuve que hacer para clase de paso lo pongo aquí.

Código (javascript) [Seleccionar]
<html>
<head>
<style>
input{
width: 42px;
}

#logs, #res, #igual{
text-align: right;
width: 180px;
}

.op, #igual{
text-align: center;
}
</style>

<script language="javascript">
function getLastchar(){
var mylogs = document.calc.logs.value;
var len = mylogs.length;

if (len){
return mylogs[len - 1];
}

return "";
}

function anadir(x){
var logstext = document.calc.logs;
var restext = document.calc.res;

if (logstext.value == "" && restext.value != ""){
restext.value = "";
}

if ((". ".indexOf(getLastchar()) > -1 && isNaN(x)) == false){
if (x.indexOf(" ") > -1){
calcular();
}

logstext.value += x;
}
}

function quitar(){
var logstext = document.calc.logs;
var num = (getLastchar() == " ") ? 3: 1;

logstext.value = logstext.value.substring(0, logstext.value.length - num);
}

function calcular() {
document.calc.res.value = eval(document.calc.logs.value);
}

function getResult(){
if (getLastchar() == " "){
document.calc.res.value = "Syntax error";
} else {
calcular();
document.calc.logs.value = "";
}
}
</script>
</head>

<body>
<form name="calc">
<input type="text" id="logs" readonly="true"/>
<br />
<input type="text" id="res" readonly="true"/>
<br />

<input type="button" value="1" onclick="anadir('1')" />
<input type="button" value="2" onclick="anadir('2')" />
<input type="button" value="3" onclick="anadir('3')" />
<input type="button" value="&larr;" onclick="quitar()" />
<br />

<input type="button" value="4" onclick="anadir('4')" />
<input type="button" value="5" onclick="anadir('5')" />
<input type="button" value="6" onclick="anadir('6')" />
<input type="button" value="-" onclick="anadir(' - ')" />
<br />

<input type="button" value="7" onclick="anadir('7')" />
<input type="button" value="8" onclick="anadir('8')" />
<input type="button" value="9" onclick="anadir('9')" />
<input type="button" value="+" onclick="anadir(' + ')" />
<br />

<input type="button" value="0" onclick="anadir('0')" />
<input type="button" value="." onclick="anadir('.')" />
<input type="button" value="*" onclick="anadir(' * ')" />
<input type="button" value="/" onclick="anadir(' / ')" />
<br />

<input type="button" id="igual" value="=" onclick="getResult()" />
</form>
</body>
</html>


DoEvents! :P