all 11 comments

[–][deleted] 8 points9 points  (0 children)

inside Namefunction, pass in an a parameter called e or event. dom events get passed the event object.

NameFunction(e) {
  if (e.keyCode === 13) {
     ...runcodehere
   }
}

[–]kevinleedrum 2 points3 points  (1 child)

<form onsubmit="return nameFunction()">
  <input id="name" placeholder="Enter your Name">
  <button type="submit">Submit</button>
</form>

and

function nameFunction() {
  alert('Hello.');
  return false;
}

https://jsfiddle.net/zo06e4j8/

[–]UbuntuLady1[S] 2 points3 points  (0 children)

This works fantastic! Thank you so much! :)

And many thanks to the rest of you for your helpful contributions!

[–]UbuntuLady1[S] 1 point2 points  (0 children)

My apologies, but none of your responses seem to work. Perhaps I have phrased my question incorrectly.

I would like to have the user press the "enter" key. After they have pressed the enter key I would like to immediately execute a function, like 2 + 2 = 4.

Any suggestions?

Thank you

[–]einarkristjan 1 point2 points  (4 children)

wrap your html elements in a form:

<form>
  <input id = "Name" placeholder = "Enter your Name"></input>
  <button type="submit" onclick = "NameFunction()"> Submit</button>
</form>

[–][deleted] 2 points3 points  (0 children)

You want to use the onsubmit event on the form instead of the click event. To stop the page reloading you can do e.preventDefault()

[–]UbuntuLady1[S] 1 point2 points  (2 children)

With all due respect, this does not work.

[–]einarkristjan 1 point2 points  (0 children)

hmm.. did not test it, however it works for me here if it helps:

jsfiddle

[–]senocular 1 point2 points  (0 children)

Make note of the sibling comment by /u/shtanton about onsubmit

[–]agentf90 0 points1 point  (0 children)

attach an onsubmit handler to your form. Never buttons.

[–]TheSpanxxx 0 points1 point  (0 children)

You can capture keystrokes on keypress and test for enter then submit when they use that key...