Reputation: 4572
Currently I'm working on a feature for a project and event.keyCode appears doesn't work for "on input" trigger. I'm using Google Chrome 31 and jQuery 1.10.2.
Here's what I tried inside my method:
input.on('input', function(event){
console.log("event.charCode: " + event.charCode);
console.log("event.keyCode: " + event.keyCode);
console.log("event.which: " + event.which);
console.log("window.event ? event.keyCode : event.which: " + window.event ? event.keyCode : event.which);
});
I get undefined
for all this methods. Am I doing something wrong or this is a jQuery / Javascript issue? Here you can find the fiddle.
I want that my input fires when user paste something inside it or change, by any way, the input content.
p.s: my method works as expected, the only thing that doesn't work is...this.
Upvotes: 13
Views: 27107
Reputation: 810
The event input does not have the keycode, but you can use the inputType property that way.
console.log(event.inputType);
event.inputType == "deleteContentBackward" // Backspace
event.inputType == "deleteContentForward" // Delete
event.inputType == "insertText" // When insert character
Upvotes: 8
Reputation: 79
You can use a better way to achieve the same thing without bother yourself with key's events, and that by adding a hidden input, and then track its change events to get the key pressed and use it, that way you don't have to worry about key codes, or anything else.
Upvotes: 0
Reputation: 477
That is because you are using onkeypress instead of onkeydown!
Try doing it with onkeydown and you will be able to access e.keyCode.
so instead of:
<input onkeypress="getKeyValue()"/>
You should do:
<input onkeydown="getKeyValue()"/>
I hope this helps, good luck mate!
Upvotes: 1
Reputation: 333
Try the use of addEventListener
, where you can specify the name of the event as string and include the action event as parameters:
let keyCode;
input.addEventListener('keydown', (e) => {
keyCode = e.keyCode
});
input.addEventListener('input', (e) => {
console.log(keyCode)
})
Upvotes: 0
Reputation: 873
Check this Fiddle
I'm not sure is that what you want but here you go
input.on('keyup keydown copy', function(event){
console.log("Code: " + event.keyCode);
console.log("Code: " + event.which);
console.log("Code: " + window.event ? event.keyCode : event.which);
});
Upvotes: 1
Reputation: 3939
I think it's because your event isn't correct, you're matching an "input" event for the input.
This might be what you're after (notice the paste
event):
jQuery(function () {
jQuery("#post-input").on('keyup', function(event){
if(!(event.ctrlKey || $(this).data('skipkeyup'))) {
console.log('keyup', event);
} else {
$(this).data('skipkeyup', true)
}
}).on('paste', function (event) {
console.log('paste event', event);
}).on('keydown', function(){
$(this).data('skipkeyup', false)
})
});
Upvotes: 2
Reputation: 248
Use can use keydown Event
input.on('keydown ', function(event){
console.log("Code: " + event.which);
});
Upvotes: 5