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
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
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:
autofocus
attribute on inputform
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments