Reputation: 29
First post on here as a new work in progress studying developer. :)
Over on Scrimba I got tasked with creating a simple temperature converter from F to C.
I understand their solution but can't seem to figure out why mine keeps returning as NaN. I get that it's not a number but I thought I did using parseInt().
Any help is greatly appreciated!
Working Solution by Them
document.getElementById("btn").addEventListener("click", function() {
let fahrenheitTemp = document.getElementById("temperature").value;
fahrenheitTemp = parseInt(fahrenheitTemp);
document.getElementById("result").textContent = (( fahrenheitTemp - 32 ) * 5/9).toFixed(2);
})
My Solution Issue
const convertBtn = document.querySelector(`#btn`);
let fahrenheitTemp = document.querySelector(`#temperature`).value;
const result = document.querySelector(`#result`);
function tempConversion() {
fahrenheitTemp = parseInt(fahrenheitTemp);
result.textContent = ((fahrenheitTemp - 32) * 5/9).toFixed(2);
}
convertBtn.addEventListener(`click`, tempConversion);
Upvotes: 1
Views: 158
Reputation: 2804
I think your problem lies in this line:
fahrenheitTemp = document.getElementById("temperature").value;
You are getting a value into a "regular" variable.
It has no "live" connection to the HTML element.
Try, instead:
fahrenheitTemp = document.getElementById("temperature");
and, in your function, instead of:
fahrenheitTemp = parseInt(fahrenheitTemp);
use:
fahrenheitTemp = parseInt(fahrenheitTemp.value);
Upvotes: 1
Reputation: 3730
I think this may work for you..
function FernhtToCelcs() {
let feren = $("#temp")[0].value;
let celcs = (( feren - 32 ) * 5/9).toFixed(2);
document.getElementById("tempincec").innerHTML = celcs + ' C';
}
input {
width: 50px;
height: 20px;
}
button {
background: #0095ff;
border: none;
border-radius: 3px;
padding: 7px;
color: white;
cursor: pointer;
}
#tempincec {
font-weight: 700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="temp">Temprature in fahrenheit : </label>
<input type="number" id="temp" name="temp">
<button onclick="FernhtToCelcs()">Convert</button>
</div>
<p>Temprature in celcius : <span id="tempincec"></span></p>
Upvotes: 1