Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript function when enter is pressed - JavaScript only no Jquery

Hello I am trying to run a javascript function when I press enter. Here is my code so far

MY HTML

<!DOCTYPE html>
<html>

<head>
    <title>JS Bin</title>
</head>

<body>
    <div>
        <form id="inputForm">
            <label for="userInput">Input : </label>
            <span id="userInputSpan">
                <input type="text" id="userInput" onkeydown="readInput(this)" />
            </span>
        </form>
    </div>
</body>

</html>

MY JAVASCRIPT

function readInput(e) {
    if (e.keyCode == 13) { // 13 is enter key
        // Execute code here.
        // var temp = e.value;
        // console.log(temp);
        alert(e.value);
    }
}

Here is my JSBin

like image 783
gkmohit Avatar asked Aug 25 '26 05:08

gkmohit


1 Answers

You're passing this to the event handler and using it as event object.

Pass the element instance and event object to the event handler.

<input type="text" id="userInput" onkeydown="readInput(this, event)" />
                                                       ^^^^  ^^^^^

And get them in the handler

function readInput(el, e) {
                   ^^  ^
// el: Element
// e: Event object

Updated JSBin

window.onload = function() {
  document.getElementById("userInput").focus();
};

function readInput(el, e) {
  if (e.keyCode == 13) {
    console.log(el.value);
  }
}
<div>
  <form id="inputForm">
    <label for="userInput">Input :</label>
    <span id="userInputSpan">
      <input type="text" id="userInput" onkeydown="readInput(this, event)"/>
    </span>
  </form>
</div>

Suggestions:

  1. Use DOMContentLoaded event instead of using onload.
  2. Use addEventListener to bind event
  3. To set focus on page load, use autofocus attribute on input
  4. To prevent form from submit, use return false; or event.preventDefault() from event handler.

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('userInput').addEventListener('keydown', function(e) {
    if (e.keyCode == 13) {
      console.log(this.value);
      
      e.preventDefault(); // Prevent default action i.e. submit form
      // return false;
    }
  }, false);
});
<div>
  <form id="inputForm">
    <label for="userInput">Input :</label>
    <span id="userInputSpan">
      <input type="text" id="userInput" autofocus />
    </span>
  </form>
</div>
like image 190
Tushar Avatar answered Aug 26 '26 18:08

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!