user4027720
user4027720

Reputation:

Having trouble getting number submitted with enter key without reloading entire page

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
        }
    }
}

Upvotes: 0

Views: 35

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

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
        }
    }
}

Upvotes: 0

Nicolai Schmid
Nicolai Schmid

Reputation: 1092

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>

Upvotes: 1

Related Questions