Search code examples
javascripthtmlcssbuttonenter

Mapping the enter key to a button in HTML/CSS/JS


I have a small form in which you have to submit a score, which is a number, then i have a script which processes the number.

The form is like so:

<form  name ="input2" style="margin-left: 30%; margin-right: 30%; margin-bottom:5%">
  Score:
  <input type="text" id="score" name="score" maxlength="3" onkeydown="if(event.keyCode==13) changePlayer();" patern="\d"><br>
  <input id = "submit" type="button" value="Submit" name="Submit" class="btn btn-primary" onclick="changePlayer(); return false"/>
  <input type="button" name="Cancel" class="btn btn-primary" value="Cancel"/>
</form>

I enter the number in a text box, and then when i click the submit button, the function processes the number. The thing is, i want the same thing to happen when i press enter, but instead, the page refreshes, and the whole thing starts over, i lose the data.

How can i sort of map the enter key to the button, or the function, without it refreshing the page?


Solution

  • Just replace <input id = "submit" type="button" to <input id = "submit" type="submit". You don't need the check.

    function changePlayer(score) {
      alert(input2.score.value);
    }
    <form name="input2" style="margin-left: 30%; margin-right: 30%; margin-bottom:5%" onsubmit="changePlayer();return false;">
      Score:
      <input type="text" id="score" name="score" maxlength="3" patern="\d"><br>
      <input id = "submit" type="submit" value="Submit" name="Submit" class="btn btn-primary" onclick="changePlayer(); return false"/>
      <input type="button" name="Cancel" class="btn btn-primary" value="Cancel"/>
    </form>