Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
Use conditional statement to write a JavaScript calculator

I'm new to JavaScript. I did a simple calculator that has 2 inputs values with 4 buttons of operators. How can I fix this JavaScript so that it can count the numbers based on different operators and display the correct output? How to write it using if else condition or switch cases?

Now I have pressed every button it only shows the output with sum only.

function count() {
  var n1 = parseFloat(document.getElementById("num1").value);
  var n2 = parseFloat(document.getElementById("num2").value);
  var optr = document.getElementById("operator").value;

  let result;

  if (optr == '+') {
    result = n1 + n2;
  } else if (optr == '-') {
    result = n1 - n2;
  } else if (optr == '*') {
    result = n1 * n2;
  } else {
    result = n1 / n2;
  }

  document.getElementById("output").innerHTML = "Total is: " + result;
}
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>

<input type="button" value="+" onclick="count()" id="operator">
<input type="button" value="-" onclick="count()" id="operator">
<input type="button" value="*" onclick="count()" id="operator">
<input type="button" value="/" onclick="count()" id="operator">

<p id="output"></p>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There are many ways to achieve what you want. Here is one that I have prepared by modifying/simplifying your original code:

const in1 = document.getElementById("num1"),
  in2 = document.getElementById("num2");
document.addEventListener("click", function(ev) {
  if (ev.target.classList.contains("operator")) {
    let optr = ev.target.value,
      n1 = +in1.value,
      n2 = +in2.value,
      result;
    if (optr == '+') result = n1 + n2;
    else if (optr == '-') result = n1 - n2;
    else if (optr == '*') result = n1 * n2;
    else result = n1 / n2;
    document.getElementById("output").innerHTML = "Total is: " + result;
  }
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>

<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">

<p id="output"></p>

A few remarks:

  • id attributes must always be unique on a page. I replaced the ids in your buttons by class attributes.
  • the values of your input elements must be evaluated at the time the operator button is clicked.
  • the conversion from text to numerical values is done implicitly by applying the unary + operator in front of in1.value and in2.value.
  • instead of assigning the handler function through the html-onclick attribute I used a delegated event attachment: the click event is attached to the whole document but will only cause an action if the actual clicked element (ev.target) has the word "operator" in its class list.
about 4 years ago · Juan Pablo Isaza Relatório

0

Switch case or If/else. Both is right. But I prefer the switch case version, because it is cleaner. Following @CarstenMassmann's answer, here is the switch case path:

const in1 = document.getElementById("num1");
const in2 = document.getElementById("num2");

document.addEventListener("click", function(e) {
  
  if (e.target.classList.contains("operator")) {
    const optr = e.target.value
    const n1 =+ in1.value;
    const n2 =+ in2.value;
    let result = 'i dont know';
    
    switch (optr) {
      case '+':
        result = n1 + n2
        break;
      case '-':
        result = n1 - n2
        break;
      case '*':
        result = n1 * n2;
        break;
      case '/':
        result = n1 / n2;
    }
    document.getElementById("output").innerHTML = "= " + result;
  }
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>

<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">

<p id="output"></p>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda