0

Below is my code. I want to make a calculator using javascript. The script will check weather you enter a diget. If not it will display a message on the screen saying to enter one. However I want the paragragp "answer" to display the message. I cant seem to get the innerHTML to work. Any help in explainging the matter would be great. Thanks in advance.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function calculate(){
    var number1 = document.getElementById("num1").value;
    var number2 = document.getElementById("num2").value;
    var line = "Enter a diget";

    if(number1==null || number1==""){
        //alert("Please enter a diget to calculate!");
        document.getElementById("answer").innerHTML= line;

        return false;   
    }
    if(number2==null || number2==""){
        alert("Please enter a diget to calculate!");
        return false;   
    }

    //alert("Hey there!");
}
</script>
</head>

<body>

<form onSubmit="calculate();" method="post" id="calculateForm">
<label id="no1">Number 1</label> <input type="text" id="num1"/>
<label id="no2">Number 2</label> <input type="text" id="num2"/>
<br/>
<p id="answer"></p>
<br/><br/>
<input type="submit" value="Calculate"/>

</form>


</body>
</html>
2
Contributors
2
Replies
9
Views
2 Years
Discussion Span
Last Post by ZeroEddy
0

I think your logic is working OK. I am not sure why you are using a form in this case. You really dont want the form to post. Here is a modified version that appears to be working as expected.

<body>
<label id="no1">Number 1</label> <input type="text" id="num1"/>
<label id="no2">Number 2</label> <input type="text" id="num2"/>
<br/>
<p id="answer"></p>
<br/><br/>
<input type="submit" onclick="calculate()"/>

<script>
function calculate(){
    var number1 = document.getElementById("num1").value;
    var number2 = document.getElementById("num2").value;
    var line = "Enter a diget";
    if(number1==null || number1==""){
        //alert("Please enter a diget to calculate!");
        document.getElementById("answer").innerHTML= line;
        return false;   
    }
    if(number2==null || number2==""){
        alert("Please enter a diget to calculate!");
        return false;   
    }
}
</script>
</body>
0

Thank you so much. So it was the form tags that were preventing it from working originally ya.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.