0

In my code example when you put your cursor in one of the two input fields and then press ENTER on your keyboard, a timestamp number is displayed in a div underneath. Press ENTER again and it changes.

If you take one of the text fields out so there's only one, then form seems to post (reload the page).

I can't figure out why this happens when there's only one input field.

function handleKeyPress(event) {
  if (event.keyCode == 13)
    document.getElementById('theButton').click();
}
function theFunc() {
  document.getElementById("theTime").innerHTML = Math.floor(Date.now());
}
<form>
  <input type="text" name="textInput" onKeyPress="handleKeyPress(event)"><br>
  <input type="text" name="textInput2" onKeyPress="handleKeyPress(event)"><br>
  <input type="button" value="Submit" id="theButton" onclick="theFunc()">
</form>

<div id="theTime"></div>
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53
  • 1
    It appears when only one input is on a form pressing enter will submit the form. http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2 "When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form." As @Will pointed out, adding event.preventDefault() to your code will prevent it from submitting. This code will prevent event propagation at the input's keypress handler before the submit event handler has a chance to fire. – Matthew Thurston Jan 31 '18 at 01:15
  • Thanks for the explanation. The only problem with `event.preventDefault` is that it won't allow ANY text to be entered. I tried adding it after `if (event.keyCode == 13)` but the form still submits. – Daniel Williams Jan 31 '18 at 02:29
  • what browser are you using? I'm running my fiddle in chrome 63 and no submit on enter keypress. My prevent default is in the event.keyCode == 13 condtional which maybe helps https://jsfiddle.net/3c9neqb1/ – Matthew Thurston Jan 31 '18 at 02:37
  • Firefox, and after more research I believe it's a problem unique to FF. – Daniel Williams Jan 31 '18 at 09:56

1 Answers1

0

Event.preventDefault()

function handleKeyPress(event) {
  if (event.keyCode == 13)
    event.preventDefault(); // magic
    document.getElementById('theButton').click();
}

function theFunc() {
  document.getElementById("theTime").innerHTML = Math.floor(Date.now());
}
<form>
  <input type="text" name="textInput" onKeyPress="handleKeyPress(event)"><br>
  <input type="button" value="Submit" id="theButton" onclick="theFunc()">
</form>

<div id="theTime"></div>
Will
  • 3,201
  • 1
  • 19
  • 17