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

JavaScript: Pressing enter on a text input invoking a function

http://codepen.io/abdulahhamzic/pen/YqMQwB

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?

Answer

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) {
      alert(myFormEl.myText.value);
      e.preventDefault(); // Don't forget this!
    }, false);
  }

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

Comments