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;
}
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>