Suppose I am catching a keyup event with jQuery on an input field. Now I am doing various things with the event, for example reacting to the tab or enter key. Now I want to determine if a key like tab, control, alt, shift was pressed or a key that actually alters the input like letters, numbers, punctuation etc.
Is there any way to determine this? How do I make sure to check all the right keys any user anywhere could press?
I hope my problem is clear.
Well, I was a little fast there with closing the question. There is still a problem. My solution so far (JSFiddle):
$('input').keyup(function(e) {
var lastValue = '';
if(typeof $(this).attr('data-last-value') != 'undefined' && $(this).attr('data-last-value') != '') {
lastValue = $(this).attr('data-last-value');
}
if(lastValue != $(this).val()) {
//This is what I wanted.
}
$(this).attr('data-last-value', $(this).val());
});
Problem: If the user for example entered 'hello' into the input, then selects the 'h' and presses the h-key, the script does not recognize it as one of the desired key presses, because the value was not altered. IS there any way around this behavior?
Maybe one of possible solutions would be to save length of input before altering the input and on some event check the new lengh i.e.:
var inputsLength = {};
$(window).keydown(function (e){
var input = e.eventTarget,
name = input.name,
oldLength = inputsLength[name];
if (!oldLength) {
inputsLength[name] = input.length
}
if (oldLength !== input.length) {
//something change
} else {
//everything is the same
}
if (e.ctrlKey) alert("control");
});
Alternative solution for your updated question would be to use "input" event which captures only what you really want in this situation.
$(window).on('input', function(e) {
//Do what you need
});
P.S. have in mind that this does not work IE < 9 and is a little buggy in IE 9. But for your needs I think it should be a good fit