3

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

gkmohit
  • 690
  • 2
  • 12
  • 28
  • Possible duplicate of [How to detect pressing enter on keyboard using jquery?](http://stackoverflow.com/questions/979662/how-to-detect-pressing-enter-on-keyboard-using-jquery) – Keval Bhatt Nov 17 '15 at 04:48
  • @KevalBhatt I am not allowed to use Jquery unfortunately . . Jquery would make life so much easier if I were allowed to use it :( – gkmohit Nov 17 '15 at 04:52
  • 1
    What is the reason for not being allowed to use jquery? – Morgan Green Nov 17 '15 at 04:57
  • @MorganGreen it is just the assignment requirement :) I was stuck with this issue, hence I asked :) – gkmohit Nov 17 '15 at 04:59

4 Answers4

7

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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
2

Here is the plain javascript I used. Hope it helps you.

document.onkeyup = function(e){
    if(e){
        var key = window.event ? e.keyCode : e.which;
    }else{
        var key = window.event ? event.keyCode : event.which;
    }
    if (key == '13') {
        //Code you would like to execute
    }
}
0

Rather, I'd suggest not to embed JavaScript in HTML.

document.addEventListener('keydown', function(e) {
  if ( e.keyCode == 13 ) {
    var ele = document.getElementById('userInput');
    alert(ele.value);
  }
});
<form id="inputForm" >
  <label for="userInput">datt1939 : </label>
  <span id="userInputSpan">
    <input type="text" id="userInput">
  </span>
</form>

Since StackOverflow sandbox prevents alert from firing, here's a JSFiddle.

Leo
  • 13,428
  • 5
  • 43
  • 61
  • I like the approach, but it does not seem to work :/ – gkmohit Nov 17 '15 at 04:43
  • @gkmohit It does work. StackOverflow prevents the `alert` from firing, maybe for security concerns. – Leo Nov 17 '15 at 04:48
  • do you think you could add jsfiddle ? :) it would make it easier :o – gkmohit Nov 17 '15 at 04:54
  • @gkmohit It'll not work if you include the script in ``, use `DOMContentLoaded` or move the script to the end of ``. – Tushar Nov 17 '15 at 04:58
  • I understand what you have done now :), but what if I dont want a response when just enter is pressed ? :) that is where your response is a little out of topic :) – gkmohit Nov 17 '15 at 04:58
  • @Leo The event should be added on `#userInput`, not on whole `document`. – Tushar Nov 17 '15 at 04:59
  • @Tushar, I have the script in an external file :) – gkmohit Nov 17 '15 at 05:00
  • @gkmohit You are wrapping the `input` within a `form`. So that's the browser's default behavior, submit the form, when you press enter on an input field. If you don't want it, you could either remove the `form` wrapper, or listen to form's `submit` event and `return false` in the listener. – Leo Nov 17 '15 at 05:01
  • OR `event.preventDefault();` in the handler. – Tushar Nov 17 '15 at 05:02
  • @Tushar yep, `preventDefault()`, instead of `return false` – Leo Nov 17 '15 at 05:03
0

There are couple of ways it can be done

Inline Event

<input type="text" value="" onKeyDown="if(event.keyCode==13) alert('Inline Event');" size="20" id="demo1" placeholder="Inline Event">

Unobtrusive Code using addEventListener

<input type="text" id="demo2" value="" size="20" placeholder="Using addEventListener">

Unobtrusive Code Calling a function

<input type="text" id="demo3" value="" onKeyUp="executeEvent(this,value)" size="20" placeholder="Seperate Handler">

JS

Attaching addEventListener to the DOM element

document.getElementById('demo2').addEventListener('keydown',function(event) {
    if (event.keyCode == 13) {
        alert('5');
    }
})

executeEvent function

function executeEvent(elem,value){
 console.log(elem)
if (event.keyCode == 13) {
        alert('You entered ' +elem.value);
    }
}

Here is JSFIDDLE

brk
  • 48,835
  • 10
  • 56
  • 78