Detecting the value on input - javascript

Having an input element
<input type="text">
if i add keydown event on it , it will work with state x - 1 value of input e.g
var x = document.getElementsByTagName("input")[0];
x.addEventListener("keydown",function(){
alert(x.value);
},false);
if i input "a" , it will print empty string , when i add "b" it wont print "ab" but "a" ( state - 1 )
Is there any simple way how to retrieve current value not previous?

Use input instead of keydown event.
If you require older browser support then you should also listen for keyup and mouseup (drag/drop) events.

Use keyup event or keypress event.
Reason is simple, when you are typing, there are three states.
When the key is pressed and held(even for a very short time). Here, the input field is not yet updated. This is keydown
keyup is when the key is released. That is when the input field is updated.
keypress is keydown and keyup both combined. (For alphanumeric keys)

As pointed in other answers, you can use keyup or keypress or input if you don't need to cancel event.
If you do need to cancel event (conditionally) then keydown is the must.
var x = document.getElementsByTagName("input")[0];
x.addEventListener("keydown",function(e){
//alert(x.value);
console.log(x.value + String.fromCharCode(e.which || e.keyCode);
},false);
The event doesn't support character value but you can receive it from keyCode.

Related

Why does KeyDown event lag one character behind? [duplicate]

If I type 'St', by the time I press the t, if I output the input of textfield.value in the onkeypress/onkeydown functions, I only get 'S'.
Why is this? How do I get rid of this lag?
use the keyup event instead of keypress. keydown will show the before-keystroke value, as will keypress (apparently).
Within the keypress event, it's still possible to prevent the typed character from registering, so the input's value canot be updated until after the keypress event. You can use the keyup event instead, or use window.setTimeout() to set up a delay.
Because the keystroke is not registered until keyup event occurs. So you should detect onkeyup event instead of onkeypress.

How to change input/textarea value with custom keyboard event and keyCode?

I would like to populate a textarea by triggering keyboard events, such as keydown (I'm doing this for a test case).
I have added a snippet (below) to show the code I'm using to create and trigger the event. The event fires, but the textarea never receives the value of keyCode which is the letter A.
What do I need to do to see the letter in the textarea? I'm currently running the snippet in the Chrome console but it should also work in IE9.
var t = document.getElementById('foo');
// Event creation
var event = document.createEvent('HTMLEvents');
event.initEvent('keydown', true, true);
event.keyCode = 65;
event.which = 65;
// Listener for demo purpose
t.addEventListener('keydown', function (e) {
document.getElementById('fired').value = e.type + ' fired';
});
// Event trigger
t.dispatchEvent(event);
<textarea id="foo"></textarea>
<br>
<input id="fired" value="">
The keydown event is fired when a key is pressed down but it's not the responsible for write the data in the DOM elements.
The thing is; If the user writes on the <textarea> first the character is added to elements value and then the keyDownevent is triggered. However in your case you're directly triggering the event so the first step which is adding the character to the value for <textarea> is not happening.
You have two options, do it in the browser way write the value and then dispatch the event
t.value = t.value + String.fromCharCode(e.keyCode);
t.addEventListener('keydown', function (e) {
document.getElementById('fired').value = e.type + ' fired';
});
Or also you can write the value of the <textarea> on the keyDown event:
// Listener for demo purpose
t.addEventListener('keydown', function (e) {
t.value = t.value + String.fromCharCode(e.keyCode);
document.getElementById('fired').value = e.type + ' fired';
});
however if you want to use this second approach for user interaction it's a nonsense because in the case that the users inputs the data, the data will be write it twice (one for the user input and the another one in the event).
Hope this helps,
Javascript sending key codes to a <textarea> element
I had a look around and this seems more relevant than my non-relevant answer before. Sorry about that. I know this is jquery, but the premise is the same.
adding this in the event would work
document.getElementById('foo').innerHTML += String.fromCharCode(e.keyCode);
here it is in pure javascript jsfiddle
Why does not the value change after triggering keydown?
In short: you can't change the value of input/texarea with dispatching KeyboardEvent programmatically.
How actually do chars come into input? On MDN you can find the description of Keyboardevent sequence (assuming that preventDefault is not called):
A keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true.
If the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down.
A keyup event is fired once the key is released. This completes the process.
So, keydown leads to input event by default. But that is true only for trusted events:
Most untrusted events will not trigger default actions, with the exception of the click event... All other untrusted events behave as if the preventDefault() method had been called on that event.
Basically trusted events are those initiated by a user and untrusted events are initiated with a script. In most browsers, each event has an attribute isTrusted indicating if the event is trusted or not.
And how to test KeyboardEvents on inputs then?
Well, first of all, think if you really need a KeyboardEvent handler. Maybe you can do everything in InputEvent handler. That means that you can just set the value of the input in your tests and then trigger InputEvent.
If you still need KeyboardEvent handler than it depends on what is going on in it. E.g. if you call preventDefault in certain conditions then you can check if it was called or not in a test using a spy. Here is an example with sinon as a spy and chai as assertion library.
const myEvent = new KeyboardEvent('keydown', { key: 'a' })
sinon.spy(myEvent, 'preventDefault')
document.getElementById('foo').dispatchEvent(myEvent)
expect(myEvent.preventDefault.calledOnce).to.equal(true)

Problems with grabbing proper value of input on keydown/keyup

I'm working on triggering events on certain key combinations that check the value of the input they were triggered in.
The problem I'm running into is that it's possible to trigger a keypress or a keydown AND type a character without triggering a keyup.
Conversely only the keyup event can read the value of the input with the newly inputted character because both the keydown and keypress fire before the character is added into the input.
JSFiddle Demo
(Note: Press shift and any other character. If you hold shift and then press and release another character the keyup event will fire, but if you press and release shift at the same time as the other key, the keyup event will not fire.)
The only solutions I can think of are triggering the keyup event one the keydown event, but this can cause problems other places.
Unfortunately I also cannot just assume that because they pressed that key combination that the input field contains what I want, as they may enter the hotkey when there are other characters in the input.
Which leaves me with the thought that I would have to check the length of the input and if it equals zero and they just pressed that hotkey, that it would fire.
But I was wondering if there's a better way of doing this?
The Keypress event seems to fire consistently. The problematic key-combinations fail to fire Keyup, but they DO fire an Input event (which, like Keyup, comes after the input value has changed). Input, however, doesn't carry information about the actual keystroke.
I don't know what conditions you're actually looking for with regards to the contents of the input. But listening for Keypress and then getting the new input contents upon the next Input event sounds like it may be what you need.
Something like:
var hotkey = false;
var lastChar = '';
$('#in').on('keypress', function(e) {
hotkey = ((e.which > 16 || e.which < 16) && e.shiftKey);
lastChar = e.which;
});
$('#in').on('input', function(e) {
if (hotkey)
$("#out").append('<div>' + lastChar + ' + shiftKey triggered ' + '<br/> INPUT: ' + $("#in").val() + '</div>');
});

Javascript, key press value is always one character behind the latest?

If I type 'St', by the time I press the t, if I output the input of textfield.value in the onkeypress/onkeydown functions, I only get 'S'.
Why is this? How do I get rid of this lag?
use the keyup event instead of keypress. keydown will show the before-keystroke value, as will keypress (apparently).
Within the keypress event, it's still possible to prevent the typed character from registering, so the input's value canot be updated until after the keypress event. You can use the keyup event instead, or use window.setTimeout() to set up a delay.
Because the keystroke is not registered until keyup event occurs. So you should detect onkeyup event instead of onkeypress.

onKeyPress Vs. onKeyUp and onKeyDown

What is the difference between these three events? Upon googling I found that:
The onKeyDown event is triggered when the user presses a key.
The onKeyUp event is triggered when the user releases a key.
The onKeyPress event is triggered when the user presses & releases a key
(onKeyDown followed by onKeyUp).
I understand the first two, but isn't onKeyPress the same as onKeyUp? Is it possible to release a key (onKeyUp) without pressing it (onKeyDown)?
This is a bit confusing, can someone clear this up for me?
NOTE KeyPress is now deprecated. Use KeyDown instead.
KeyPress, KeyUp and KeyDown are analogous to, respectively: Click, MouseUp, and MouseDown.
Down happens first
Press happens second (when text is entered)
Up happens last (when text input is complete).
The exception is webkit, which has an extra event in there:
keydown
keypress
textInput
keyup
Below is a snippet you can use to see for yourself when the events get fired:
window.addEventListener("keyup", log);
window.addEventListener("keypress", log);
window.addEventListener("keydown", log);
function log(event){
console.log( event.type );
}
Check here for the archived link originally used in this answer.
From that link:
In theory, the onKeyDown and onKeyUp events represent keys being pressed or released, while the onKeyPress event represents a character being typed. The implementation of the theory is not same in all browsers.
Most of the answers here are focused more on theory than practical matters and there's some big differences between keyup and keypress as it pertains to input field values, at least in Firefox (tested in 43).
If the user types 1 into an empty input element:
The value of the input element will be an empty string (old value) inside the keypress handler
The value of the input element will be 1 (new value) inside the keyup handler.
This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.
Scenario:
The user types 12345 into an input element.
The user selects the text 12345.
The user types the letter A.
When the keypress event fires after entering the letter A, the text box now contains only the letter A.
But:
Field.val() is 12345.
$Field.val().length is 5
The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).
So it seems that the browser (Firefox 43) erases the user's selection, then fires the keypress event, then updates the fields contents, then fires keyup.
First, they have different meaning: they fire:
KeyDown – when a key was pushed down
KeyUp – when a pushed button was released, and after the value of input/textarea is updated (the only one among these)
KeyPress – between those and doesn't actually mean a key was pushed and released (see below). Not only it has inconsistent semantics, it was deprecated, so one shouldn't probably use it (see also this summary)
Second, some keys fire some of these events and don't fire others. For instance,
KeyPress ignores delete, arrows, PgUp/PgDn, home/end, ctrl, alt, shift etc while KeyDown and KeyUp don't (see details about esc below);
when you switch window via alt+tab in Windows, only KeyDown for alt fires because window switching happens before any other event (and KeyDown for tab is prevented by system, I suppose, at least in Chrome 71).
Also, you should keep in mind that event.keyCode (and event.which) usually have same value for KeyDown and KeyUp but different one for KeyPress. Try the playground I've created. By the way, I've noticed quite a quirk: in Chrome, when I press ctrl+a and the input/textarea is empty, for KeyPress fires with event.keyCode (and event.which) equal to 1! (when the input is not empty, it doesn't fire at all).
Note: these days, using event.key is the most useful option as it is standardized across browsers, OSes and events (afaik).
Finally, there's some pragmatics:
For handling arrows, you'll probably need to use onKeyDown: if user holds ↓, KeyDown fires several times (while KeyUp fires only once when they release the button). Also, in some cases you can easily prevent propagation of KeyDown but can't (or can't that easily) prevent propagation of KeyUp (for instance, if you want to submit on enter without adding newline to the text field).
Suprisingly, when you hold a key, say in textarea, both KeyPress and KeyDown fire multiple times (Chrome 71), I'd use KeyDown if I need the event that fires multiple times and KeyUp for single key release.
KeyDown is usually better for games when you have to provide better responsiveness to their actions.
esc is usually processed via KeyDown: KeyPress doesn't fire and KeyUp behaves differently for inputs and textareas in different browsers (mostly due to loss of focus)
If you'd like to adjust height of a text area to the content, you probably won't use onKeyDown but rather onKeyPress (PS ok, it's actually better to use onChange for this case).
I've used all 3 in my project but unfortunately may have forgotten some of pragmatics. (to be noted: there's also input and change events)
onkeydown is fired when the key is down (like in shortcuts; for example, in Ctrl+A, Ctrl is held 'down'.
onkeyup is fired when the key is released (including modifier/etc keys)
onkeypress is fired as a combination of onkeydown and onkeyup, or depending on keyboard repeat (when onkeyup isn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!)
textInput (webkit only) is fired when some text is entered (for example, Shift+A would enter uppercase 'A', but Ctrl+A would select text and not enter any text input. In that case, all other events are fired)
This article by Jan Wolter is the best piece I have came across, you can find the archived copy here if link is dead.
It explains all browser key events really well,
The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.
To understand the difference between keydown and keypress, it is useful to distinguish between characters and keys. A key is a physical button on the computer's keyboard. A character is a symbol typed by pressing a button. On a US keyboard, hitting the 4 key while holding down the Shift key typically produces a "dollar sign" character. This is not necessarily the case on every keyboard in the world. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. In practice, this is not always the way it is implemented.
For a while, some browers fired an additional event, called textInput, immediately after keypress. Early versions of the DOM 3 standard intended this as a replacement for the keypress event, but the whole notion was later revoked. Webkit supported this between versions 525 and 533, and I'm told IE supported it, but I never detected that, possibly because Webkit required it to be called textInput while IE called it textinput.
There is also an event called input, supported by all browsers, which is fired just after a change is made to to a textarea or input field. Typically keypress will fire, then the typed character will appear in the text area, then input will fire. The input event doesn't actually give any information about what key was typed - you'd have to inspect the textbox to figure it out what changed - so we don't really consider it a key event and don't really document it here. Though it was originally defined only for textareas and input boxes, I believe there is some movement toward generalizing it to fire on other types of objects as well.
It seems that onkeypress and onkeydown do the same (whithin the small difference of shortcut keys already mentioned above).
You can try this:
<textarea type="text" onkeypress="this.value=this.value + 'onkeypress '"></textarea>
<textarea type="text" onkeydown="this.value=this.value + 'onkeydown '" ></textarea>
<textarea type="text" onkeyup="this.value=this.value + 'onkeyup '" ></textarea>
And you will see that the events onkeypress and onkeydown are both triggered while the key is pressed and not when the key is pressed.
The difference is that the event is triggered not once but many times (as long as you hold the key pressed). Be aware of that and handle them accordingly.
Updated Answer:
KeyDown
Fires multiple times when you hold keys down.
Fires meta key.
KeyPress
Fires multiple times when you hold keys down.
Does not fire meta keys.
KeyUp
Fires once at the end when you release key.
Fires meta key.
This is the behavior in both addEventListener and jQuery.
https://jsbin.com/vebaholamu/1/edit?js,console,output <-- try example
(answer has been edited with correct response, screenshot & example)
The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.
Just wanted to share a curiosity:
when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!
For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !
Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!
Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK
and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.
Basically, these events act differently on different browser type and version, I created a little jsBin test and you can check the console for find out how these events behavior for your targeted environment, hope this help. http://jsbin.com/zipivadu/10/edit
The difference which I observed between keyup and keydown is
if we attach a eventhandler for keydown event and log the input box value i.e
(e.target.value) it returns whatever the value was before keydown event
But if we attach a eventhandler for keyup event and log the input box value
it returns the latest value including the key which was pressed
LETS UNDERSTAND WITH EXAMPLE
// the latest keypressed is not shown in e.target.value
// when keydown event handler is executed
// since until the keyup is not triggered
// the input box will not have that character in its value
const searchCitiesEleKeyDown = document.querySelector("#searchCities");
searchCitiesEleKeyDown.addEventListener("keydown", (e) => {
console.log(e.target.value);
});
// but in case of keyup event the e.target.value prints
// the text box content with the latest character pressed
// since as soon as the keyup event triggers
// the input box will have that character pressed in its value
const searchCitiesEleKeyUp = document.querySelector("#searchCities");
searchCitiesEleKeyUp.addEventListener("keyup", (e) => {
console.log(e.target.value);
});
<input type="text" id="searchCities" />
CodeSandbox Link
https://codesandbox.io/s/keydown-vs-keyup-wpj33m
A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):
$('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
Pressing:
non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress. Press Ctrl and release it:
keydown 17 17 Control
keyup 17 17 Control
keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown. Press ´ and release it in order to display a double ´´:
keydown 192 192 Dead
keydown 192 192 ´´
keypress 180 180 ´
keypress 180 180 ´
keyup 192 192 Dead
Additionally, non typing inputs (e.g. ranged <input type="range">) will still trigger all keyup, keydown and keypress events according to the pressed keys.
BLAZOR....
If you want to check which key is pressed use onkeypress OR onkeydown but if you want to get the text from the text field and then check the last key pressed for example you are scanning a barcode and you want to fire an even when the ENTER key is pressed (almost all barcode scanners send 13 "ENTER" in the last) then you should use onkeyup otherwise you will not get the text typed in the text field.
For example
<input type="text" class="form-control" #bind="#barcode" #onkeyup="BarCodeScan" placeholder="Scan" />
This will call the BarCodeScan function immediately after you will press enter by typing the code or if you scan it from scanner the BarCodeScan function will be called automatically. If you will use "onkeypress" or "onkeydown" here then the bind will not take place and you will not get the text from the text field.

Categories

Resources