Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
how to make a function to switch on the value of attributes

hey everyone so i was working to make this calculator work and i had other ways to do it but i wanted to do it in a particular way

        <form action="">
            <label for="firstVal">numberA</label><br>
            <input type="number" name="firstVal" id="firstVal"><br>
            <label for="SecondVal">numberB</label><br>
            <input type="number" name="SecondVal" id="SecondVal"><br>
            <label for="Result">Result</label><br>
            <input type="number" name="Result" id="Result"readonly><br>
            <br><br>
            <input type="button" value="+" onclick="Calculate()">
            <input type="button" value="-" onclick="Calculate()">
            <input type="button" value="x" onclick="Calculate()">
            <input type="button" value="/" onclick="Calculate()">
            <input type="button" value="C" onclick="Calculate()">
        </form>
    
var firstNum = document.getElementById("firstVal").innerHTML;
var secondNum = document.getElementById("SecondVal").innerHTML;
var Resul = document.getElementById("Result");
var Operator= document.querySelectorAll('value');


function Calculate() {
    var Sol;
    switch (Operator){
        case "+" :
            Sol=firstNum+secondNum
            console.log(Sol)
            break;
        case "-" :
            Sol=firstNum-secondNum
            console.log(Sol)
            break;
        case "x" :
            Sol=firstNum*secondNum
            console.log(Sol)
            break;
        case "/" :
            Sol=firstNum/secondNum
            console.log(Sol)
            break;
        case "C" :
            firstNum&secondNum&Resul==null
            break;
    };
};

my problem is on the switch as you see i'm trying to make a function that will determine which operation it will do based on the value of the attribute value i gave the switch statement Operator as key to check on and i don't know if im missing something or i'm doing something wrong please lemme know if there is anyway to achieve the above

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Things I changed:

  • include value of button in function call (alternatively fn(event) -> value = event.target.value)
  • get the reference to the inputs outside of the function, but since the values of numberA/B change, get the actual values every time at start of function
  • the values of the inputs are strings so convert them to numbers by prefixing + (alternatively with Number('str'))
  • calculate 'Sol' inside switch, but set as Result only once at the end of the function
  • in case 'C' - as an alternative to resetting the value of every input to an empty string simply call form.reset() and terminate function (no Result to set in this case) by calling 'return'

Suggested improvements:

  • firstNum, secondNum, firstVal, secondVal, numberA, numberB - a lot of different names :) Better stick to the same term every time
  • instead of setting click handler on every button, use submit event of form with .preventDefault()

var formElement = document.getElementById('calculate');
var firstInputElement = document.getElementById("firstVal");
var secondInputElement = document.getElementById("secondVal");
var resultInputElement = document.getElementById("Result");

function Calculate(value) {

  var nA = +firstInputElement.value;
  var nB = +secondInputElement.value;

  var Sol;

  switch (value) {
    case "+":
      Sol = nA + nB
      break;
    case "-":
      Sol = nA - nB
      break;
    case "x":
      Sol = nA * nB
      break;
    case "/":
      Sol = nA / nB
      break;
    case "C":
      formElement.reset()
      return;
  };
  resultInputElement.value = Sol
};
<form action="" id="calculate">
  <label for="firstVal">numberA</label><br>
  <input type="number" name="firstVal" id="firstVal"><br>
  <label for="SecondVal">numberB</label><br>
  <input type="number" name="secondVal" id="secondVal"><br>
  <label for="Result">Result</label><br>
  <input type="number" name="Result" id="Result" readonly><br>
  <br><br>
  <input type="button" value="+" onclick="Calculate(this.value)">
  <input type="button" value="-" onclick="Calculate(this.value)">
  <input type="button" value="x" onclick="Calculate(this.value)">
  <input type="button" value="/" onclick="Calculate(this.value)">
  <input type="button" value="C" onclick="Calculate(this.value)">
</form>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda