Абдулах Хамзиќ Абдулах Хамзиќ - 5 months ago 11
HTML Question

JavaScript: Pressing enter on a text input invoking a function


How do I make it so that when I press enter on a text input, it calls a function? I tried using this:

<input type="text" onkeypress="clickPress()">

But the problem is I only want pressing enter to call that function, not pressing any key. How do I do that?


Use a form instead (the submit event only runs once instead of every key press):

// Wrap code in a closure (global variables may mess with other JS)
(function(window, document) {
  'use strict';

  // Get the form element
  var myFormEl = document.querySelector('.my-form');
  if(myFormEl) {
    // Attach the event handler to the form element
    myFormEl.addEventListener("submit", function(e) {
      e.preventDefault(); // Don't forget this!
    }, false);

})(window, document);
<form class="my-form">
  <input type="text" name="myText">