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()
The 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).
Actually, the 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.
In regard to String.fromCharCode, simply use String.fromCharCode(event.keyCode) to get the keyCode's "human" equivalent.
The event passed to the function is an object containing all the informations about this given event, including the pressed key.
1) Use 'keyup' insted of 'keypress'.
2) lastkey.textContent = 'Last key in ASCII code: ' + String.fromCharCode(e.keyCode);
3) Don't know much about it. event parameter is added to catch the fired event. It has all the property of the fired event like for 'keyup' it has 'charcode', keycode', 'key' etc.
Related
I'm working on a project where I use javascript to create a random number of input fields with maxlength = "1" and when the user fills all of them with one letter each a submit button appears .
The problem is that when a field is filled I want the cursor to move to the next input field . I am trying to add this functionality to my input elements using an eventlistener with the onkeyup event . However when I implement this in code the cursor movement functionality is not working and when I inspect my page I see no errors .
My code :
https://jsfiddle.net/bill_sk/2t7vLc5y/2/
I would appreciate your help with this . Thank you in advance .
inputLists.forEach(input => {
input.addEventListener("keyup", ()=>{
if(input.value.length === input.maxLength && parseInt(input.id) < inputLists.length) {
document.getElementById(parseInt(input.id)+1).focus();
}
})
input.id will give you a string, so you have to parse it to int.
event should be "keyup", and not "onkeyup"
always look out for the last element in an array when you want add something to the next element in a for cycle
use the inputList variable that you initialize at the top of the function, the code will be more readable
Happy coding!
First you need to listen to the keyup event not the onkeyup event
elem.addEventListener("keyup" , evt => {
and then get the next input element like this
let el = document.getElementById(parseInt(elem.id) +1).focus();
Try "keyup" instead of "onkeyup".
If you are working on something like this, always try to find out, which part of the code is not working with console.log()
There were some other mistakes, but this works
elem.addEventListener("keyup" , evt => {
elem = evt.target
if(elem.value.length >= elem.maxLength){
let el = document.getElementById(parseInt(elem.id) +1)
el.focus();
}
});
I am new to JS and trying to learn on my own - thanks for any help!
I am trying to have a simple program respond to a click differently depending on what other key is pressed at the time of the mouse click.
I have searched far and wide and have not been able to find an answer that works for non-modifier keys alt and shift (which I have had no trouble implementing). However, I can't for the life of me figure out how to achieve the same result with a regular character key.
The example below (which I found in other comments on this site) works if the alt key is employed.
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.altKey) {
//do something, alt was down when clicked
}
});
});
However, the intuitive modification does not work.
For example, the otherwise identical code (now using event.keyCode===114) does not work (?!) when the 'r' key is pressed (nor does event.charCode===114 do the trick):
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.keyCode===114) {
//do something, alt was down when clicked
}
});
});
What went wrong?
I am able to get functionality out of a keyPress if I listen to it alone:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if(event.keyCode===114){
console.log("the 'r' key is pressed");
}
}
however nothing seems to work when I try to pair a character keypress with a mouse click or even a character keypress with a modifier keypress:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if((event.keyCode===114) && (event.altKey)){
console.log("the 'alt' and 'r' keys are pressed");
}
}
Note: I have tried keydown instead of keypress in all of these examples with no success.
Suggestions please on what I am missing or overlooking - what is problematic about pairing a character key down/press with a modifier key or a mouse click !?
Thank you!!
As I commented above, the click event does not have a property called keyCode so doing event.keyCode will not work. The only reason that control and alt work is because they are properties of the click event, event.ctrlKey and event.altKey. You can be a little more creative and use something like this maybe though I don't really know what you need:
var currKey = null;
$("#targetDiv").click(function (event) {
if (currKey != null) {
$("#targetDiv").text(currKey);
}
});
$(window).keydown(function (event) {
currKey = event.which;
});
$(window).keyup(function (event) {
currKey = null;
});
This stores the key code when keydown is fired, when keyup is fired it clears the var. The stuff in the click event is only allowed to run if the var shows something other than null.
I'm making a custom input field which should support subscript. When the user presses the down arrow + a number, then the number should be in subscript. I appended a onKeyDown and onKeyUp event listener to a content editable paragraph. Unfortunately the onKeyUp gets called when the user presses the number, which results in adding the number twice (once in subscript and once normal). How can I solve this problem?
function keyDown(event) {
var code = event.keyCode;
if (code === 40) {
option = 0;
}
}
function keyUp(event) {
var code = event.keyCode;
if (code === 40 || code === 38) {
option = -1;
}
console.log("release");
}
The onKeyPressed is not an option since this does not recognize the arrow keys in all browsers. Is there a native solution (without jQuery)?
What I usually do is to push the keyCodes into an Array on keyDown and .splice() it on keyUp.
All you have to do now is to check (probably against a pre-defined map) if the key states you desire are available in that Array.
As long as your text field has focus, any numeral key you press will be added to it in addition to whatever your keyup or keydown listeners add to it. Maybe you should take away focus from the text field on keydown if the key you are pressing is the down key and add focus back again after the keyup event has fired.
/* Keep track of the down key. */
var down=false;
/* Get the input text field. */
var input=document.getElementById("input");
input.addEventListener("keydown",keyDown);
input.addEventListener("keyup",keyUp);
/* Give focus to input. I'm not sure if this is the right way to do it, I haven't tested this code, but I know there's a way to give focus to elements and it sort of looks like this. */
input.focus();
function keyDown(event_){
switch(event_.keyCode){
case 40:
/* Once again, not sure how to unfocus, but I know you can. */
input.unfocus();
down=true;
break;
}
}
function keyUp(event_){
switch(event_.keyCode){
case 40:
/* Give focus back to input after the keyup event has fired. */
input.focus();
down=false;
break;
}
if (down){
input.value+=//The subscript version of whatever key you pressed.
}
}
Once again, I would just like to say that this code hasn't been tested and I'm not sure if focus() and unfocus() are real methods, but you get the idea. You want to momentarily stop the text field from accepting input while the down key is pressed so you can add your own special value to it without updating it's contents with the default response and then give focus back to the text field once the down key is no longer in use.
Say I have this:
<textarea id="myarea">Hello</textarea>
How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8.
And i am not looking for this:
$('#myarea').val( $("myarea").val().slice(0,-1) );
I need to simulate someone actually pressing the 'backspace' key on their keyboard.
Thanks
You can create a keydown event:
var e = jQuery.Event("keydown", { keyCode: 20 });
Then trigger it in your textarea:
$("#myarea").trigger( e );
Update:
After doing some more research and testing, I realize that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key.
To simulate the user going into that textbox and pressing that key, you would have to create a dispatch event
The dispatch event is also not globally supported. Your best bet would be to trigger the keydown event and then update the text area as intended.
I found this:
http://forum.jquery.com/topic/simulating-keypress-events (answer number 2).
Something like this should work, or at least give you an idea:
<div id="hola"></div>
$(function(){
var press = jQuery.Event("keyup");
press.ctrlKey = false;
press.which = 40;
$('#hola').keyup(function(e){
alert(e.which);
})
.trigger(press); // Trigger the event
});
Demo: http://jsfiddle.net/qtPcF/1/
You shouldn't be forcing key events in js. Try simulating the character removal instead.
const start = textarea.selectionStart - 1;
const value = textarea.value;
const newValue = value.substr(0, start) + a.substr(start);
textarea.value = newValue;
Or if you just want the event, instead call the handler directly, rather than forcing the event. This is too hacky.
I want to hook paste event for <input type="text"> and force this text to be pasted into hidden textarea (then I want to parse textarea's text and perform 'paste data from excel to gridview' action). Something like:
$('#input1').bind('paste', function(e) {
// code do paste text to textarea instead of originally targeted input
});
What cross-browser code should I write instead of comments?
Thanks.
There is this hacky solution that fires a focus event on a textarea when Ctrl and V keys or Shift and Insert keys are down. [Yes, it doesn't work for contextmenu -> past]
$(document).ready(function(){
var activeOnPaste = null;
$('#input1').keydown(function(e){
var code = e.which || e.keyCode;
if((e.ctrlKey && code == 86) || (e.shiftKey && code == 45)){
activeOnPaste = $(this);
$('#textarea').val('').focus();
}
});
$('#textarea').keyup(function(){
if(activeOnPaste != null){
$(activeOnPaste).focus();
activeOnPaste = null;
}
});
});
The code lets the pointer focus on a textarea when Ctrl and V keys are down. At that moment no text is pasted, it's pasted after this keydown function is fired so the pasted text is shown in the textarea. After that, on keyup on that textarea, #input1 will be focused.
While typing this, I see that there may be a solution for both keyboard pasting and mouse pasting, using ranges. I'll try something with that too...
You should bind a function to your input-fields onChange() event and copy its content everytime this function is called and process the data afterwards. If you are specifically interested in "pasted" content (I do not know what you are trying to do there, but generally it is a sign of bad concept to be in a situation where pasted content has to be treated additionally) you can try implementing a counter that checks the input speed (eg more than xx characters per second -> PASTE-Eventcall)