0

I'm trying to create a number game for a class assignment. The computer generates a random number and the player gets five chances to guess it. I've completed all the requirements for the assignment but I want to modify the game so that it will accept a guess by pressing the Return/Enter key (on the keyboard) , not just the button. I have been looking at Stackexchange (especially Trigger a button click with JavaScript on the Enter key in a text box) but I cannot get it to work. I don't want to use JQuery. Any suggestions would be appreciated.

Here is my code:

<head>
<script type = "text/javascript" src = "Guessing6.js"></script> 
</head>
<body>

<form action="Guessing6.js" method="get">Enter a number between 1 and 100: <br />

<input type="text" name="inputbox" onkeydown="if(event.keyCode==13) document.getElementById('mybutton').click()"/>

<input type="button" id="mybutton" value="Guess" onClick="testResults(this.form)">
</form><br />

</body>

And the relevant js:

function testResults (form) {

var TestVar = form.inputbox.value;
Community
  • 1
  • 1
  • 1
    Rather than using _onclick_, move to _onsubmit_ of the `
    ` and prevent the submission so the page does not refresh. Now any way to submit the `
    ` invokes your code.
    – Paul S. Sep 17 '13 at 01:17

3 Answers3

0

On the form use the onsubmit and return false; also use input type submit

<form onsubmit='testResults(this);return false;'>
    <input type='submit' />
</form>
Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • Great, thanks to you both. It seems to be working. Below is my code. Let me know if you see anything that looks incorrect.
    Enter a number between 1 and 100:

    –  Sep 17 '13 at 02:20
0
 function submitenter(myfield,e)
{
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13)
    {
        whatever_function_it_is();
        return false;
    }
    else
        return true;
}




<form>
 <input type="text" id="box" name="result" onKeyPress="return submitenter(this,event)"  />
 <input type="button" id="button" value="GO"  onClick="whatever_function_it_is()"  />
</form>
Rocket Chimp
  • 41
  • 2
  • 5
-4
<html>
<head>
<script>


function btn_click(){
    alert(1);
}

function key_up(e){
  if(e.keyCode == 13){
    btn_click();
  }else{
  return;
  }
}

</script>
</head>
<body>
<input type="text" onkeypress="key_up(event)">
<button onclick="btn_click()">click</button>
</body>
</html>
lv0gun9
  • 591
  • 7
  • 23
  • A small spelling mistake you have made, instead of function you have written "fucntion". correct it. – Gourav Sep 17 '13 at 01:42
  • The question says that "I don't want to use JQuery. Any suggestions would be appreciated." so think of something else. – Gourav Sep 17 '13 at 01:44
  • Thanks, this may come in handy for the next iteration. As noted, trying to do it without JQuery this time. –  Sep 17 '13 at 19:23