I'd like to make a webpage with text box without button. If i type couple of letters and push button 'Enter', comes after 1 second alert dialog box with text from text box. Everything works correct, only that aler dialog box doesn`t come after Enter, but after mouse click.
<!Doctype HTML!>
<html>
<head>
<meta charset="utf-8">
<head>6-4</head>
<script>
var keyCode = '';
var naam = '';
window.onload = function () {
var divResult = document.getElementById('divResult');
document.getElementById('txtInput').addEventListener('blur', function () {
naam = document.getElementById('txtInput').value;
document.getElementById('txtInput').onkeyup = function (e) {
keyCode = e.keyCode;
if (keyCode === 13) {
}
};
setTimeout("alert(naam);", 1000);
}, false);
};
function stopAlerts() {
clearInterval(txtNaam);
}
</script>
</head>
<body>
<h2>Type some letters in text box and push 'Enter'</h2>
<input type="text" id="txtInput" value="" />
<div id="divResult"></div>
</body>
</html>
Just set one event on the textbox, keydown
, and move the timer into the true
block of the if
statement.
Notes:
title
element in the head
section. You cannot nest a head
element
within anther head
element.value=""
.setTimeout()
is not advised.
Instead pass a function to be executed.script
in the head
and then setting up a
window.onload
event handler for the code that should run
automatically when the DOM is ready, move your script
to just
before the closing body
tag and remove the onload
event handler
and just execute the code you want run.e.target
.h2
without having an h1
is semantically incorrect and
will cause issues for those who rely on assistive technologies. Never
use an HTML element because of the way the browser styles it by
default. Styling is CSS' job. If you want some big, bold text and are
not starting a new section, stay away from heading elements and just
style the text.<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>6-4</title>
<style>
h1 { font-size:1.1em; }
</style>
</head>
<body>
<h1>Type some letters in text box and push 'Enter'</h1>
<input type="text" id="txtInput">
<div id="divResult"></div>
<script>
var divResult = document.getElementById('divResult');
document.getElementById('txtInput').addEventListener('keydown', function (e) {
if (e.key === "Enter") {
setTimeout(function(){ alert(e.target.value); }, 1000);
}
}, false);
</script>
</body>
</html>