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

393
Vistas
Input is a number, but is treated as string, How to convert to make a sum and use it in a Try and catch throw error to check the entries JavaScript

I need your help to go to a try and catch statements and throw errors in an if/else, with user input. The problem is that "the else block" does not execute. The main objective is to check if it is number to parseInt and then use the input values to a sum. I first check if it is empty, Then I check if it is letter or strings and after, I check if it is a number at last, in the else statement.

The problem is that the input is always treated as a string, and never goes to the else statement. How to fix that, once all inputs are numbers ?

Obs.: The catch block and both throw errors are working fine.

window.onload = () => {
  const button = document.getElementById('button')
  button.addEventListener('click', verifyEntries)
}

function verifyEntries () {
  try {
    const value1 = document.getElementById('value1').value;
    const value2 = document.getElementById('value2').value;

    if (value1 === '' || value2 === ''){ // check if the input is empty
      throw new Error(' value 1 and value 2 must be filled !'); // **this line execute**
    } else if (typeof value1 !== 'number' && typeof value2 !== 'number'){ // check if is "alphabetical"
      throw new Error(' both values should be numbers'); // **this line execute**line 17
    } else { // **this block does not executes - the input stays as strings**
      const result = parseInt(value1) + parseInt(value2);
      document.getElementById('result').innerHTML = `Resultado: ${result}`; // I get the error message line 17
    }
  } catch (error) {
    alert('Atention!  ' + error)
  } finally {
    document.getElementById('value1').value = ''
    document.getElementById('value2').value = ''
  }
}
<body>
  <p>Inform two numbers to sum:</p>
  <label for='value1'>Valor 1:</label>
  <input type='text' id='value1'>
  <label for='value2'>Valor 2:</label>
  <input type='text' id='value2'>
  <button id='button'>Sum</button>
  <p id='result'></p>
  <script src="script.js"></script>
</body>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

thank you guys for your help. After searching a lot in this site, I found a good alternative, I have checked and is working fine. Take a look.

window.onload = () => {
  const button = document.getElementById('button')
  button.addEventListener('click', verifyEntries)
}

function verifyEntries () {
  try {
    const value1 = Number(document.getElementById('value1').value);
    const value2 = Number(document.getElementById('value2').value);
    console.log(value1, value2);

    if (value1 == '' || value2 == ''){ // check if the input is empty
      throw new Error(' value 1 and value 2 must be filled !'); // this line execute
    } else if (isNaN(value1) || isNaN(value2)){ // check if is "alphabetical"
      throw new Error(' both values should be numbers'); // this line execute
    } else {
      //  parseInt(value1) && parseInt(value2) - this line is not necessary.
      console.log(value1, value2);
      const result = (value1) + (value2);
      document.getElementById('result').innerHTML = `Resultado: ${result}`; // is working now 
    }
  } catch (error) {
    alert('Atention!  ' + error)
  } finally {
    document.getElementById('value1').value = ''
    document.getElementById('value2').value = ''
  }
}

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