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

98
Visualizações
Mathematical Function Returning NaN Error (JavaScript)

I am trying to fix a NaN error.

When running the code on the console it gives me the correct answer. However, when I try to print it on a HTML H1 tag the code returns a NaN error.

I tried to use native functions (ie.: parseFloat(), .toString();), but it didn't work as planned.

Could you shed a light, please?

const tempConvert = parseFloat (document.querySelector('input'));

function convertTemp(tempConvert) {
    switch (slt.value) {
        case 'farenheit':
            document.querySelector('h1').innerHTML = `${convertCToF(tempConvert)} Fº`;
            break;
        case 'kelvin':
            document.querySelector('h1').innerHTML = `${convertCToK(tempConvert)} Kº`;
            break;
        default:
            alert('Selec an option.');
            break;
    }
}


function convertCToF(tempC) {
    return tempC * 1.8 + 32;
}

function convertCToK(tempC) {
    return tempC + 273.15;
}

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

0

You have to get input.value, not input. document.querySelector('input') is going to give you the HTML Element of input. If you console.log that, you will see it has a bunch of properties and among them is value, which contains the text inside the input tag.

Also, it's generally a better idea to use innerText than to use innerHTML whenever possible due to security reasons.

const slt = {
  value: 'farenheit'
}

function convertTemp(tempConvert) {
  console.log("Hello");
  switch (slt.value) {
    case 'farenheit':
      document.querySelector('h1').innerText = `${convertCToF(tempConvert)} Fº`;
      break;
    case 'kelvin':
      document.querySelector('h1').innerText = `${convertCToK(tempConvert)} Kº`;
      break;
    default:
      alert('Selec an option.');
      break;
  }
}

document.querySelector("#myBtn").addEventListener('click', () => convertTemp(document.querySelector('input').value));

function convertCToF(tempC) {
  return tempC * 1.8 + 32;
}

function convertCToK(tempC) {
  return tempC + 273.15;
}
<input type='text' />
<button id="myBtn">Convert</button>

<h1>Result Here</h1>

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