Fares Fares - 3 months ago 17
HTML Question

Key number press to submit form

It's a page for Handheld Scanner Website (PocketPC), so for easy handling of the device when number 1 is pressed in the keyboard, bottom 1 is submitted. I don't know why it's not working for me.



function check1(e) {
if (e.KeyCode == 49) {
document.forms[0].submit();
}
}

<form id="form1" name="form1" method="post" action="test.php">
<input type="submit" name="button" id="button" value="Submit" onkeypress="check1(event)" />
</form>





Thanks

Answer

You need to attach event to the entire document and not just that <input> in this case. This is because you want to trigger the action event if the <input> is not in focus. You code activated only if it is on focus.

I have made the change:

HAVE A LOOK AT THE SNIPPET:

document.addEventListener("keypress", function(event) {
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if (keycode == '49') {
    document.forms[0].submit();
  }
});
<form id="form1" name="form1" method="post" action="test.php">
  <input type="submit" name="button" id="button" value="Submit" onkeypress="check1(event)" />
</form>