I have a code which is suppose to update the number of remaining characters left when the user types in a text input
. The code is triggered using keypress
event. The problem is the code is triggered only after 2 keypress
. Why does that happen?
I have a code to show the key of ASCII code but the character always shows 8 and shows when I press backspace. And how to use String.fromCharCode(event.keycode} ;
method.
Why is a event
parameter added to a function
?
How does e.keycode
know it is displaying the keycode
of the user's input.
Code Sample
HTML
<div id="page">
<h1>List King</h1>
<form id="messageForm">
<h2>My profile</h2>
<textarea id="message"></textarea>
<div id="charactersLeft">180 characters</div>
<div id="lastKey"></div>
</form>
</div>
JavaScript
var el; // Declare variables
function charCount(e) { // Declare function
var textEntered, charDisplay, counter, lastkey; // Declare variables
textEntered = document.getElementById('message').value; // User's text
charDisplay = document.getElementById('charactersLeft'); // Counter element
counter = (180 - (textEntered.length)); // Num of chars left
charDisplay.textContent = counter; // Show chars left
lastkey = document.getElementById('lastKey'); // Get last key used
lastkey.textContent = 'Last key in ASCII code: ' + e.keyCode; // Create msg
}
el = document.getElementById('message'); // Get msg element
el.addEventListener('keypress', charCount, false); // keypress -call charCount()
keypress
event is triggered before the input's value is updated, this is why the counter is not up to date. I'd suggest to listen to the input
event if you don't need the keyCode. You can also listen to keyup
(but the update won't be straight forward) or the combination of keypress
and keyup
(from "How to get text of an input text box during onKeyPress?", I updated the right answer's fiddle).keypress
event doesn't seem to be triggered when you press backspace. That been said, an other solution to ignore "muted" keys ("backspace", "shift", "command" and so on) is to listen to the "input" event (but you won't have access to event.keyCode
). Otherwise you can also ignore your code when the keyCode is not relevant.String.fromCharCode(event.keyCode)
to get the keyCode's "human" equivalent.