Javascript + HTML calculator

Asked

Viewed 30,696 times

2

I have to do a Javascript calculator for class, and I’m facing several errors. I wanted to do that first write the number 1 and without following choose which operation to do, after the chosen operation enter the second number, and at the end click the "Send" button that will show the result in alert, but I’m finding it difficult to do the same. Could you help me?

<html>
   <head>
      <title>Aula</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style type="text/css">
      body{
         background: gray url(Image/mosaico.jpg) repeat;
      }
      </style>
      <link href="estilos.css" rel="stylesheet" type="text/css">
      <script>
      //alert("Ola mundo");
      function ola(x){
         var f=document.getElementById("frm");
         var txt = f.txtnome;
         txt.value = "Ola "+txt.value;
      }

      function soma() {
         //alert("1");
         var f=document.getElementById("frm");
         var n1=document.getElementById("n1").value;
         var n2=document.getElementById("n2").value;
         var soma = n1 + n2 ;
         alert(soma);
      }

      function subtracao() {
         var f=document.getElementById("frm");
         var n1=document.getElementById("n1").value;
         var n2=document.getElementById("n2").value;
         var soma = n1 - n2 ;
         alert(soma);
      } 

      function multiplicacao() {
         var f=document.getElementById("frm");
         var n1=document.getElementById("n1").value;
         var n2=document.getElementById("n2").value;
         var soma = n1 * n2 ;
         alert(soma);
      } 

      function divisao() {
         var f=document.getElementById("frm");
         var n1=document.getElementById("n1").value;
         var n2=document.getElementById("n2").value;
         var soma = n1 / n2 ;
         alert(soma);
      } 

      function mostrarresultados() {

      }

      function limpar(){
         //alert("1");
         var f=document.getElementById("frm");
         var n1 = f.n1;
         var n2 = f.n2;

         n1.value = "";
         n2.value = "";
      }
      </script>

   </head>
   <body>
   <form id="frm"  >
      <div id="container">
         <div id="topo"> 
            <h1>Aula de Web</h1>
         </div>

         <div id="menu">
         </div>

         <div id="left">
            <div class="bloco">
               <span>Nome:</span>
               <input type="text" name="txtnome" placeholder="Introduza o seu nome">
               <input id="enviar" type="button" value="Enviar" onClick="ola('Ola')">
            </div>
            <div class="bloco1">
               <span>Introduza os numeros:</span><br>
               <input type="text" size="2" name="n1" placeholder="n1"><br>
               <input type="text" size="2"  name="n2" placeholder="n2"><br><br>
               <input type="button" value="+" onClick="soma()">
               <input type="button" value="-" onClick="subtracao('')">
               <input type="button" value="*" onClick="multiplicacao('')">
               <input type="button" value="/" onClick="divisao('')"><br><br>
               <input type="button" value="Limpar" onClick="limpar()"/>
               <input type="button" value="Enviar" onClick="ola('Ola')">
            </div>
         </div>

         <div id="right">
            <img id="mario1" src="Image/mario1.jpg" alt=""/>
            <img id="mario2" src="Image/mario2.jpg" alt=""/>      
         </div>

         <div id="bottom">

         </div>
      </div>
   </form>
   </body>
</html>
  • You’d have to redo all the code, 'cause your calculator’s all set up.

  • the problem is that the way I rode nothing this working unfortunately :(

2 answers

1

function writeNumber(elementId) {
  var outputValueTo = document.getElementById('field1');

  if (outputValueTo.value == '0' || outputValueTo.value == 'Syntax error') {
    outputValueTo.value = elementId.textContent;
  } else {

    outputValueTo.value += elementId.textContent;
  }
}

function cleartxt() {
  document.getElementById('field1').value = '0';
  document.getElementById('dec').disabled = false;
}

function setOperator(elementId) {
  var outputValueTo = document.getElementById('field1');
  if (outputValueTo.value == '0' || outputValueTo.value == 'Syntax error') {
    outputValueTo.value = '0';
  } else {
    outputValueTo.value += elementId.textContent;
    document.getElementById('dec').disabled = false;
  }
}

function setDecimal(elementId, status) {
  var outputValueTo = document.getElementById('field1');
  outputValueTo.value += elementId.textContent;
  document.getElementById('dec').disabled = status;
}

function calculate() {

  try {

    var field1txt = document.getElementById('field1');
    if (field1txt.value != '') {
      var calculateResult = eval(field1txt.value);
      field1txt.value = calculateResult;
    }
  } catch (err) {

    field1txt.value = 'Syntax error';

  }

}

function removeLastNumber() {

  var field1txt = document.getElementById('field1');

  if (field1txt.value.length == 1 || field1txt.value == '0' || field1txt.value == 'Syntax error') {
    field1txt.value = '0';
    document.getElementById('dec').disabled = false;
  } else {
    field1txt.value = field1txt.value.substring(0, field1txt.value.length - 1);
  }
}
body {
  font-family: Verdana, sans-serif;
  font-size: 0.8em;
  margin: 0px;
  background: black;
}

nav,
section,
article {
  margin: 5px;
  padding: 8px;
}

#content {
  text-align: center;
}

header,
footer {
  background-color: Red;
  color: green;
  padding: 5px;
  margin: 0;
}

h1 {
  text-align: center;
}

button {
  width: 60px;
  text-align: center;
  font-size: 35px;
  background-color: red;
  color: black;
  border: cornflowerblue solid 1px;
  box-shadow: 1px 2px 3px 1px green;
  text-shadow: 1px 1px 3px green;
}

input {
  width: 250px;
  font-size: 30px;
  background-color: red;
  color: black;
  border: cornflowerblue solid 1px;
  text-align: right;
  box-shadow: 1px 2px 3px 1px green;
  text-shadow: 1px 1px 3px blue;
}

nav ul {
  margin: 0;
  padding: 0;
}

nav ul li {
  display: inline;
  margin: 5px;
}
<section>
  <article>
    <div id='content'>
      <div id='content-app'>
        <input type='text' id='field1' readonly value='0' />
        <br /><br />
        <button onclick='writeNumber(this)' id='n1'>1</button>
        <button onclick='writeNumber(this)' id='n2'>2</button>
        <button onclick='writeNumber(this)' id='n3'>3</button>
        <button onclick='writeNumber(this)' id='n4'>4</button>
        <br /><br />
        <button onclick='writeNumber(this)' id='n5'>5</button>
        <button onclick='writeNumber(this)' id='n6'>6</button>
        <button onclick='writeNumber(this)' id='n7'>7</button>
        <button onclick='writeNumber(this)' id='n8'>8</button>
        <br /><br />
        <button onclick='writeNumber(this)' id='n9'>9</button>
        <button onclick='writeNumber(this)' id='n0'>0</button>
        <button onclick='setDecimal(this,true)' id='dec'>.</button>
        <button onclick='setOperator(this)' id='sum'>+</button>
        <br /><br />
        <button onclick='setOperator(this)' id='sustract'>-</button>
        <button onclick='setOperator(this)' id='multi'>*</button>
        <button onclick='setOperator(this)' id='divide'>/</button>
        <button onclick='cleartxt()' id='C'>C</button>
        <br /><br />
        <button onclick='calculate()' id='calcular' style='width:190px'>=</button>
        <button onclick='removeLastNumber()' id='removeLast'>B</button>
      </div>
    </div>
    <br />
    <br /><br />
  </article>
</section>

1


As your calculator is already mounted and not functional, I will suggest these changes to make it work and simplify your code.

1. Create only 1 function to do the calculations, without having to do 1 function for each mathematical operation:

function calc(e){

   var operacao = e.value;

   var n1=parseFloat(document.getElementById("n1").value);
   var n2=parseFloat(document.getElementById("n2").value);

   var calculo = eval(n1+operacao+n2);

   if(!isNaN(calculo)){
      alert(calculo);
   }

}

2. Add onclick on each mathematical operation button calling the above function:

<input type="button" value="+" onclick="calc(this)">
<input type="button" value="-" onclick="calc(this)">
<input type="button" value="*" onclick="calc(this)">
<input type="button" value="/" onclick="calc(this)">

In the end, your code would be this:

function calc(e){
   
   var operacao = e.value;
   
   var n1=parseFloat(document.getElementById("n1").value);
   var n2=parseFloat(document.getElementById("n2").value);
   
   var calculo = eval(n1+operacao+n2);

   if(!isNaN(calculo)){
      alert(calculo);
   }
  
}

function ola(x){
   var f=document.getElementById("frm");
   var txt = f.txtnome;
   txt.value = "Ola "+txt.value;
}

function limpar(){
   //alert("1");
   var f=document.getElementById("frm");
   var n1 = f.n1;
   var n2 = f.n2;
   n1.value = "";
   n2.value = "";
}
<form id="frm"  >
   <div id="container">
      <div id="topo"> 
         <h1>Aula de Web</h1>
      </div>
      <div id="menu">
      </div>
      <div id="left">
         <div class="bloco">
            <span>Nome:</span>
            <input type="text" name="txtnome" placeholder="Introduza o seu nome">
            <input id="enviar" type="button" value="Enviar" onClick="ola('Ola')">
         </div>
         <div class="bloco1">
            <span>Introduza os numeros:</span><br>
            <input type="text" size="2" id="n1" placeholder="n1"><br>
            <input type="text" size="2"  id="n2" placeholder="n2"><br><br>
            <input type="button" value="+" onClick="calc(this)">
            <input type="button" value="-" onClick="calc(this)">
            <input type="button" value="*" onClick="calc(this)">
            <input type="button" value="/" onClick="calc(this)">
            <br><br>
            <input type="button" value="Limpar" onClick="limpar()"/>
            <input type="button" value="Enviar" onClick="ola('Ola')">
         </div>
      </div>
      <div id="right">
         <img id="mario1" src="Image/mario1.jpg" alt=""/>
         <img id="mario2" src="Image/mario2.jpg" alt=""/>      
      </div>
      <div id="bottom">
      </div>
   </div>
</form>

  • You saved me a lot of trouble !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.