Search code examples
javascriptformsfunctiononkeydown

Javascript onkeydown function runs and then display goes away


first time on the website, anyway my problem is that when I use onkeydown and then use GetChar to check if the enter key was pressed, when operAtion runs,the results of the function only shows on the screen for about a second and then goes away, if the user uses the onclick (clicks the enter button), then this problem doesnt occur. How do I get the result of operAtion to stay on the screen when onkeydown is used. The website is sqrtcalc.comze.com if you want to see what I mean

sqrtcalc

<!DOCTYPE html>

<html>
<head>
<title>Square Root Calculator</title>

    <script language="javascript">
        function operAtion (form){
            var x = form.inputbox.value;
                if (isNaN(x)){
                    //document.write("lawl");
                    var y = "Enter a number";
                    document.getElementById("failsafe").innerHTML = y;
                    document.getElementById("demo").innerHTML = "";
                } else if (x < 0){
                    var y = "Number must be positive";
                    document.getElementById("failsafe").innerHTML = y;
                    document.getElementById("demo").innerHTML = "";
                } else if (x == ""){
                    var y = "uhm, you didnt enter anything";
                    document.getElementById("failsafe").innerHTML = y;
                    document.getElementById("demo").innerHTML = "";
                } else {
                    var y = Math.pow(x, 1/2)
                    document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
                    document.getElementById("failsafe").innerHTML = "";
                }
        }
        function GetChar (event,form){
            var keyCode = event.keyCode;
                if (keyCode == 13){
                operAtion(form);
                }
        }
    </script>

<p></p>
</head>
<body>

<form name="myform" action="" method="get" style = "font-size:50px"><strong>Square Root Calculator</strong></br>
    </br>
<input type="text" name="inputbox" value = "" onkeydown = "GetChar(event,this.form);"> </br>
    </br>
<input id="button" type="button" name="button" value="     Enter      " onclick="operAtion(this.form)" >
</form>

<h1 id = "failsafe"></h1>
</br>
</br>
</br>
<h1 id = "demo"></h1>
</br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br>
<img border="0"  src="http://counter.rapidcounter.com/counter/1353157574/a"; ALIGN="middle" HSPACE="4" VSPACE="2" style = "padding-left:1400px;">

</body>
</html>

Solution

  • Add this code:

            window.onload = function(){
                document.getElementById("myform").onsubmit = function(){
                    return false;
                }
            }
    

    And add the id attribute id="myform" to the <form> tag.