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

4
  • Possible duplicate of How to detect pressing enter on keyboard using jquery? Commented Nov 17, 2015 at 4:48
  • @KevalBhatt I am not allowed to use Jquery unfortunately . . Jquery would make life so much easier if I were allowed to use it :( Commented Nov 17, 2015 at 4:52
  • 1
    What is the reason for not being allowed to use jquery? Commented Nov 17, 2015 at 4:57
  • @MorganGreen it is just the assignment requirement :) I was stuck with this issue, hence I asked :) Commented Nov 17, 2015 at 4:59

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

3 Comments

perfect, also I am guessing e is for event and el is for element ? :)
@gkmohit yes...you can check the key code with e.keyCode and any manipulation on the element using el.
@gkmohit I've added the description of both el and e.
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
    }
}

1 Comment

Use only var key = e.keyCode ? e.keyCode : e.which;
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.

10 Comments

I like the approach, but it does not seem to work :/
@gkmohit It does work. StackOverflow prevents the alert from firing, maybe for security concerns.
do you think you could add jsfiddle ? :) it would make it easier :o
@gkmohit It'll not work if you include the script in <head>, use DOMContentLoaded or move the script to the end of <body>.
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 :)
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.