0

I have a simple JavaScript program that converts celsius to fahreinheit and vice versa. But one function does not work and returns NaN.

<script type="text/javascript">
    function CtoF() {
        c = parseInt(document.getElementById("celsiusTemp").value);
        fah = c * (9 / 5) + 32;
        document.getElementById("resC").innerHTML = fah;
    }

    function FtoC() {
        f = parseInt(document.getElementById("celsiusTemp").value);
        cel = (f - 32) * (5 / 2);
        document.getElementById("resF").innerHTML = cel;
    }
</script>
<body>
    <form>
        <p>Insert celsius temperatur:
            <input type="text" id="celsiusTemp" />
            <br>
        </p>
        <p>Insert fahrenheit temperatur:
            <input type="text" id="fahreheitTemp" />
            <br>
        </p>
        <input type="button" class="btn btn-success" onClick="CtoF()" Value="Calc Fahrenheit" />
        <input type="button" class="btn btn-warning" onClick="FtoC()" Value="Calc Celsius" />
    </form>
    <br/>
    <p>The Result is :
        <br/>
        <p>Result celsius to fahreinhet:</p><span id="resC"></span>

        <p>Result fahreinhet to celsius:</p><span id="resF"></span>

</body>

Why do I get NaN when calculating celsius)

Thanks!!

code-jaff
  • 9,230
  • 4
  • 35
  • 56

2 Answers2

5

You probably need to replace:

f = parseInt(document.getElementById("celsiusTemp").value);

With:

f = parseInt(document.getElementById("fahreheitTemp").value);

If you click the Calc Celsius button, it will try to get a value from the Celsius field. If that's empty, the parseInt will return NaN:

isNaN(parseInt("")) === true
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
2

Because your celsius function is reading the wrong input, and since you haven't typed into that input when you test the function, it is an empty string which parseInt turns into Not A Number.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335