I want text I enter in a text field immediately to be shown in a div:
function func() {
document.getElementById("query").innerHTML = document.getElementById("keyword").value;
}
window.onload = function() {
keyword.onkeydown = function(e) {
func();
}
}
<input type="text" id="keyword" size="40">
<div id="query"></div>
I want text I enter in a text field immediately to be shown in a div:
function func() {
document.getElementById("query").innerHTML = document.getElementById("keyword").value;
}
window.onload = function() {
keyword.onkeydown = function(e) {
func();
}
}
<input type="text" id="keyword" size="40">
<div id="query"></div>
It works, the only problem is, it is displayed with a delay.
So if I enter "abc", it only shows "ab". I need to enter another character, for example "abcd", so that it shows "abc".
The last character is always missing.
Here you can try it out: http://jsfiddle.net/285cz0np/
Share Improve this question edited Nov 26, 2015 at 22:47 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Nov 26, 2015 at 22:00 Evgenij ReznikEvgenij Reznik 18.6k42 gold badges115 silver badges191 bronze badges 1 |3 Answers
Reset to default 15The event is being fired onkeydown
. Since the value of the input element hasn't changed yet, you aren't seeing the results.
You could change it to onkeyup
, instead: (updated example). Or you could set a delay before calling the function.
Alternatively, you could also listen to the input
event:
Example Here
document.getElementById("keyword").addEventListener('input', function (e) {
document.getElementById("query").textContent = e.target.value;
});
The issue is because the input text value, not change until you release the key.
by using setTimeout
you let the browser to update the value, before running your function (func
)
I recommend not to change onkeyup
, becuase you want onkeydown
, this solution will still work using the onkeydown
event
keyword.onkeydown = function (e) {
setTimeout(func,0)
}
Update Example jsFiddle: http://jsfiddle.net/285cz0np/1/
I recommend you to change to input
event. For example, if the user paste from the clipboard (by using only the mouse), your event will not fire.
This is because the event that fires the function is onkeydown
, so when the key is pressed down, the function reads the value of the text area. At this time it reads the data, the key that is pressed hasn't been added to the actual value yet.
An easy fix is to change the event to onkeyup
because by the time the key is in the up state, the value of that key will be added to the value.
window.onload = function () {
keyword.onkeyup = function (e) {
func();
}
}
key*
event. – Felix Kling Commented Nov 26, 2015 at 22:03