1
I have a problem in the design of a calculator I’m developing
Everything from the calculator works, except when printing the values in the input
screen: the values appear and disappear in less than 1 second, leaving the input
blank.
Follow the code used:
function putNum(num){
document.getElementById('tela').value = document.getElementById('tela').value + num;
}
function limpar(){
document.getElementById('tela').value = document.getElementById('tela').value = " ";
}
function oper(oprt){
if(document.getElementById('tela').value != ""){
document.getElementById('tela').value = document.getElementById('tela').value + oprt;
} else {
alert('Antes de realizar operações, digite um número')
}
}
function result(){
document.getElementById('tela').value = eval(document.getElementById('tela').value);
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculadora com Botões</title>
<script type='text/javascript' src='calculadora-botoes.js'></script>
</head>
<body>
<main>
<form>
<div id='calculadora'>
<div id='cabecalho'>
<input type="textarea" name="tela" id="tela" maxlength="18">
<input type="submit" id="resul" value="=" onclick='result()'>
</div>
<table>
<tr> <!--Operadores-->
<td>
<input type="button" id="c" value="C" onclick='limpar()'>
</td>
<td>
<input type="button" class='oper' value="+" onclick='oper("+")'>
</td>
<td>
<input type="button" class='oper' value="-" onclick='oper("-")'>
</td>
<td>
<input type="button" class='oper' value="*" onclick='oper("*")'>
</td>
<td>
<input type="button" class='oper' value="/" onclick='oper("/")'>
</td>
</tr>
<tr><!--Números-->
<td></td>
<td>
<input type="button" class='num' value="1" onclick='putNum(1)'>
</td>
<td>
<input type="button" class='num' value="2" onclick='putNum(2)'>
</td>
<td>
<input type="button" class='num' value="3" onclick='putNum(3)'>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" class='num' value="4" onclick='putNum(4)'>
</td>
<td>
<input type="button" class='num' value="5" onclick='putNum(5)'>
</td>
<td>
<input type="button" class='num' value="6" onclick='putNum(6)'>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" class='num' value="7" onclick='putNum(7)'>
</td>
<td>
<input type="button" class='num' value="8" onclick='putNum(8)'>
</td>
<td>
<input type="button" class='num' value="9" onclick='putNum(9)'>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" class='num' value="0" onclick='putNum(0)'>
</td>
</tr>
</table>
</div>
</form>
</main>
</body>
</html>
You don’t have to use
form
in the code since you will not send anything to the server.– Sam
The problem is in the button
=
who is submitting the form. Change the type totype="button"
.– Sam