it seems simple, but I couldn't figure how to intercept numbers on javascript from Document DOM
$(document).keypress(function (e) {
if (e.keyCode == xx) {
alert();
}
});
Numbers are 48 through 57, so...
$(document).keypress(function (e) {
var key = e.keyCode || e.charCode;
if (key >= 48 && key <= 57) {
alert('You pressed ' + (key - 48));
}
});
See demo
Source: http://www.quirksmode.org/js/keys.html
Keypress events yield a keyCode of 0 in Firefox, and the ASCII character value everywhere else. Keypress events yield a charCode of the ASCII character value in Firefox. Therefore, you should use (e.keyCode || e.charCode) to get the character value.
Also note that your code also wouldn't work because alert should accept one argument. In Firefox, at least, calling alert with no arguments throws an exception.
With those two issues fixed, your code will now be:
$(document).keypress(function (e) {
if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
alert('something');
}
});
Example: http://jsfiddle.net/gRrk6/
$(document).keydown(function(event){
if(event.keyCode == 13) {
alert('you pressed enter');}
});
replace 13 with the keys code, see here for details:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
you should notice the differences between events [ keyCode, charCode, which ]
and this test page affected by the browser i.e i tested it on safari
the onKeyPress always empty
JavaScript Event KeyCode Test Page
Related
I want catch an event for Alt+c or something like that. My code is
html
<input type="text" id="name"/>
JavaScript
$("#name").keydown(function(e) {
if(e.keyCode == 67 && e.keyCode == 18){alert(e.keyCode);}
});
where is the problem? How it works on both Chrome & firefox?
You need to check for e.altKey instead:
if(e.altKey && e.keyCode == 67){alert(e.keyCode);}
Basically, you are checking for two codes as the same time. The event (e) has several values you can work with ... including altKey which is a boolean (true or false) ...
Try ... watching the e.altKey and the e.keyCode values.
$("#name").keydown(function(e) {
if(e.altKey && e.keyCode == 67) {
alert(e.keyCode);
}
});
With the right version of jQuery, there should be no issue between browsers.
$(document).keydown(function(e) {
//console.log(e.keyCode); If you want to check other keys code
if(e.keyCode == 67 || e.keyCode == 18){
console.log("alt or c pressed");
}
});
You can work around this to check if the two keys are pressed at the same time. I sujest you to use an aux var set to zero wich increase his value when keydown event triggered and decrease it when keyup.
In the snippet below, Ctrl+Enter (event.which == 13) is working. However, Ctrl+R (event.which == 9) is not.
if ($('.selector')) {
$(document).keypress(function(event) {
if ( event.altKey && event.which == 13 ) {
$('.link a').trigger('click');
} else if ( event.altKey && event.which == 82 ) {
$('.link a').trigger('click');
} else {
return false;
}
});
}
The problem with your code is the keyPress listener behaves differently and uses a different set of keyCode. For keyPress the r key is 114 while for keyDown it is 82.
Also another problem is browser's default reload function will override your function because keypress is executed after you release the key. To solve this, change keypress to keydown.
$(document).keydown(function(e){
if(e.which === 82 && e.ctrlKey){ //keycode is 82 for keydown
alert("Pressed!");
e.preventDefault(); //stop browser from reloading
}
});
http://jsfiddle.net/DerekL/3P9NS/show
PS: It seems like Firefox is ignoring e.preventDefault (which by W3C standards it should). The best thing to do to support all browsers is to choose another combination, or use ctrl + alt + r.
if(e.which === 82 && e.ctrlKey && e.altKey){
Based on some quick testing at http://api.jquery.com/event.which/, it seems you want event.which == 82, not event.which == 9. Although most browsers tend to use Ctrl + R to refresh the page, so this might not be the best way to handle whatever you're doing.
A cross-Browser solution to prevent Ctrl+R refresh page:
LIVE DEMO (works in Firefox, Chrome, Safari, Opera)
var keyEv = navigator.userAgent.indexOf('Firefox')>-1?["keypress",114]:["keydown",82];
$(document)[keyEv[0]](function(e) {
if ( e.ctrlKey && e.which == keyEv[1] ){
e.preventDefault();
alert("CTRL+R");
}
});
By simply testing for our navigator.userAgent you can decide what Key event listener to use and the respective R key code.
If you need to handle both R and ENTER in combination with Ctrl than you just need this little tweak:
LIVE DEMO (again all browsers :) )
var keyEv = navigator.userAgent.indexOf('Firefox')>-1?["keypress",114]:["keydown",82];
$(document)[keyEv[0]](function(e) {
var k = e.which;
if ( e.ctrlKey && k==keyEv[1] || k==13 ){ // no XBrowser issues with 13(Enter)
// so go for it!
e.preventDefault();
alert("Do something here");
}
});
I am trying to figure out when a key press is an empty space, so I did the following:
if (e.which == ' '){
}
however this does not work. Any idea why?
event.which returns the code of the character pressed. space key code is 32, so use it instead:
if (e.which === 32) {
//
}
Another way is to convert character to char code with .charCodeAt():
if (e.which === " ".charCodeAt(0)) {
//
}
CHECK: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Write a test code and alert what the keyCode is.
document.onkeypress = function(e) {
e = e || window.event;
console.log(e.keyCode || e.which);
};
Learn to debug and you would not be asking these simple questions.
jQuery would have been
$(document).keypress(
function (e) {
console.log(e.which);
}
);
Probably this is what you're looking for: (Assuming you use the keydown event.)
if(e.keyCode == '32') {
// Your code
}
jsFiddle:
http://jsfiddle.net/DeHFL/
I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:
$(textField).onKeyPress(function(e) {
if (e.which < 48 && e.which > 57)
e.preventDefault();
});
This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.
Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.
My final code looks something like this:
$(textField).onKeyPress(function(e) {
var code = e.which || e.keyCode;
if (code > 31 // is not a control key
&& (code < 37 || code > 40) // is not an arrow key
&& (code < 48 || code > 57) // is not numeric
&& (code != 46) // is not the delete key
)
e.preventDefault();
});
However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.
What am I doing wrong? Which is the best practice in terms of this kind of validation?
We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.
If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:
$("#textfield").on("keypress blur", function(e){
if ( e.type === "keypress" )
return !!String.fromCharCode(e.which).match(/^\d$/);
this.value = this.value.replace(/[^\d].+/, "");
});
Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/
Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)
Demo for arrow key to work http://jsfiddle.net/gpAUf/
This will help you.
Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)
Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?
code
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
html
<input type="text" class="hulk" value="" />
Update for copy paste stuff
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$(".hulk").bind('input propertychange', function() {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
code from another demo
$(".hulk").bind('input propertychange', function(event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
this.value = this.value.replace(/[^0-9\.]/g,'');
});
this will allow both int.
it also removes text if user copy and paste with mouse.
$(document).ready(function () {
$('#textfield').bind('keyup blur', function (e) {
if (e.type == 'keyup') {
if (parseInt($(this).val()) != $(this).val()) {
$(this).val($(this).val().slice(0, $(this).val().length - 1));
}
} else if (e.type == 'blur') {
$(this).val('');
}
});
});
For whatever reason I can't capture "SHIFT+TAB" combination.
I am using the latest jQuery.
Same result if I use other ajax/javascript, etc.
Here is a simple example that should work as I currently understand it...
event.which or event.KeyCode are always "undefined" only shiftKey exists in a scenario involving a "SHIFT+TAB" or backward keyboard traversal, traditionally inherent in windows based apps/web or otherwise...
function ShiftTab()
{
debugger;
if(event.KeyCode == 9 && event.shiftKey) // neither this line nor the following work
// if (event.which == 9 && event.shiftKey) // shift + tab, traverse backwards, using keyboard
{
return true;
}
else
{
return false;
}
}
this seems to be yet another item related to tab order that no longer works as it traditionally worked in Microsoft.Net WinForm/WebForm based apps.
If you are using jQuery, this should be how the code is working. Make sure keyCode is lower case. Also, jQuery normalizes keyCode into which:
$(document).keyup(function (e) {
if (e.which === 9 && e.shiftKey) {
ShiftTab();
}
});
If you're into terse JavaScript:
$(document).keyup(function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
jQuery 1.7+ on syntax:
$(document).on('keyup', function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
I created a function which I wired up to my button's onkeydown event. I used onkeydown, because onkeypress would not capture my tab key press
function ShiftTab(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode; // for trans-browser compatibility
if (charCode === 9) {
if (e.shiftKey) {
$('#controlName').focus();
return false;
} else {
return true;
}
}
I took this approach to deal with two specific problems:
onkeypress would not capture tab key press
When click shift-tab, shift key press would trigger function, so I had nest the shiftkey modifier check
use same code inside keypress event.
the tab changes the element between keypress and keyup.
here we get event.key = tab and event.shiftKey = true.