I’m not sure if many people would want to do this or if good reasons exist for doing this; however, I wanted to submit a form to itself without page refresh for a trivia game. So, after taking the time to research and figure it out, here is a solution.
This solution does not actually submit the form; rather, it uses two JavaScript functions to simulate submitting a form. By simulating a submission of the form rather than actually submitting the form, one can avoid a page refresh.
The first step to this process is calling a couple of JavaScript functions in the input element or another element of the form. Below is what my form element looked like for my game.
<form>
Team Name: <input id="txt1" onkeypress="return disableEnterKey(event)" onkeyup="showHint(this.value, event)" type="text" />
</form>
It may be possible to achieve the same goal by just using onkeypress=”return disableEnterKey(event)”; however, this didn’t seem to work for me. Thus, I added event as a second argument to the showHint() function (the function which does most of the work in my game), and doing this made it possible for the function to handle the form data on enter as well.
The next step is coding these two functions. Below is the disableEnterKey() function that I used to disable form submission on enter.
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
I grabbed this function off of www.bloggingdeveloper.com. This code should be included in the head section of your html file, or you can include it in a separate .js file and link to it in the head section of your html file as I did.
I included a similar block of code in my showHint() function to process the form data when the enter key is released.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key==13)//the enter key was pressed
{
//your code to run when the enter key is pressed
}
That pretty much sums up this tutorial. If you would like to see what the working example functions like, you can visit my two minute drill game. It is a game to see if you can name all 32 NFL teams in two minutes. If you play, you should be aware that you are responsible for remembering the teams that you already named, and there is no special prize or notification if you name all 32 teams in the two minute time limit.