Mark Beleski
Mark Beleski

Reputation: 55

JavaScript & DOM Logic Appears Correct but Won't Run Right

All I want to do is disable the button if there's no content in ftemp. If there is, I want the button to enable and check if it is numeric. Then I can send the ftemp to the next page. My html :

<!DOCTYPE html> 
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">

            function content()
            {
                var ftemp = document.getElementById("ftemp");
                if (ftemp.value=="")
                {
                    var convert = document.getElementById("convert").disabled=true;
                    document.getElementById("error").innerHTML = "";
                }
                else
                {
                    isNumeric()
                }
            }
            function isNumeric()
            {
                var ftemp = document.getElementById("ftemp");
                if (isNaN(ftemp))
                {
                    var convert = document.getElementById("convert").disabled=true;
                    document.getElementById("error").innerHTML = "Enter only numbers";
                }
                else 
                {
                    var convert = document.getElementById("convert").disabled=false;
                    document.getElementById("error").innerHTML = "";
                }
            } 

        </script>
    </head>
    <body onload="content()">
        <form method="get" action="celsius">
            <p>
                <label>
                    Enter a temperature in Fahrenheit:
                </label>
            </p>
            <p>
                <input required id="ftemp" title="Enter only numbers!" size="3"
                    maxlength="3" onkeyup="content()"/>
                <button id="convert" name="convert">Convert to Celsius</button>
            </p>
            <p id="error" name="error">

            </p>
        </form>
    </body>
</html>

Upvotes: 0

Views: 66

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

You have error here:

if (isNaN(ftemp))

Change it to:

if (isNaN(ftemp.value))

The ftemp is a DOM Object. You need to pass the value here.

Fiddle: http://jsbin.com/ocibuc/2

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Inside isNumeric():

You are checking: isNaN(ftemp) where ftemp is a DOM element so it cannot be a number. Change to isNaN(parseInt(ftemp.value, 10)).

Upvotes: 3

Related Questions