0

Currently I am working on a simple math game where the user hits the enter key to submit the answer to the math question. But, when enter is pressed all the variables are reset and everything is wiped out.

I know that this is probably a common question, but I have yet to see this answered for someone not trying to use a search bar. I'm just using a number input. I just want to keep the page from reloading and use my function when enter is pressed. I am really looking just to get the answer with the enter button and not refresh my page.

HTML for answer collection:

<form align= "center" id = "form">
    <input type ="number" id ="answer" value ="" autofocus>
</form>

Javascript code:

document.getElementById("answer").onkeydown = function (event){ 
    if(problems != 0){
        if(event.keyCode == 13){
            //some code in here
        }
    }
}
Gleb Kemarsky
  • 8,401
  • 6
  • 37
  • 57
  • Use `XMLHttpRequest`. Check this answer [here](http://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) – ibrahim mahrir Jan 18 '17 at 23:33

2 Answers2

1

Pretty easy solution. Your function has to return false. With that return value the usual form execution gets stoped. A better approach, as already mentioned, would be to not use a form, but just use the input itself, doing the request, if needed, with the XMLHttpRequest module -> ajax.

HTML:

<div align= "center" id = "form">
    <input type ="number" id ="answer" value ="" autofocus>
</div>
Nicolai Schmid
  • 672
  • 10
  • 26
  • I love you internet person. I have been hitting my head against a wall for I don't know how long because of this. If you haven't yet guessed I'm new to HTML. Thank you!!!! :D My life is complete. –  Jan 19 '17 at 00:06
  • No problem at all! – Nicolai Schmid Jan 19 '17 at 10:53
0
document.getElementById("answer").onkeydown = function (event)
{   
    if(problems != 0){
        if(event.keyCode == 13)
        {
            // stop the form from submitting (thus reloading the page)
            e.preventDefault();

            // number to send
            var number = this.value;

            var request = new XMLHttpRequest();
            // don't forget to fill with a valid url to your php file
            request.open("POST", "your url goes here", true);
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.onreadystatechange = function() {
                if(request.readyState == 4 && request.status == 200) {
                    //request.response holds the returned data from the server if you want to is it use it here.
                    // or pass it to another function (also here).
                }
            }
            request.send("yourInputName=" + number);
            // so you can get it using $_POST['yourInputName'] in php
        }
    }
}
ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61