KeyCode is taking wrong in mozilla - javascript

My javascript code to disable decimals in textbox ix like this
$(document).ready(function() {
$(".money-input").keypress(function (e) {
// between 0 and 9
if (e.which < 48 || e.which > 57) {
alert(1);
showAdvice(this, "Integer values only");
return (false); // stop processing
}
});
function showAdvice(obj, msg) {
$("#singleAdvice").stop(true, false).remove(); // remove any prev msg
$('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
$("#singleAdvice").delay(4000).fadeOut(1500); // show for 4 seconds, then fade out
}
});
This works perfect in Chrome. But when i go to Mozilla. Back space alos get in to that if case. So when I press back space nothing happens and error message is shown. Can anyone point out what I am doing wrong herE?

The keypress event does not fire for non-printable characters, like Esc, Ctrl, Shift, and in your case, backspace.
Use keyup() instead:
$(".money-input").keyup(function(e) {
if (e.which < 48 || e.which > 57) {
showAdvice(this, "Integer values only");
return false;
}
});
Example fiddle

Related

jquery keypress() events are not working for keyup()

Here is the code for keypress function, which is allowing only numbers
http://jsfiddle.net/lesson8/HkEuf/1/
But, for the same keycodes, keyup function is not working. I mean, if I use
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
The reason for using keyup is to get the current entered value in the textbox. If I use keyup function, I will get the current value. But, If I use keydown or keypress, I am getting the previous or existing value in the textbox
see the updated code with different functions
http://jsfiddle.net/dgireeshraju/HkEuf/7300/
this is the example with keydown, which is giving the existing value.
KeyUp fires after the character inserted only, as you can see your function is actually calling and warning message is displaying.
If you try the same code with KeyDown it will work as the event will be called before a character is inserted
//called when key is pressed in textbox
$("#quantity").keydown(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
Key up fires when the user releases a key, after the default action of that key >has been performed.
Keypress fires when an actual character is being inserted in, for >instance, a text input. It repeats while the user keeps the key depressed.
Your code is actaully working in both the cases (you can see the error message atleast ) but since this event are different so is the result. To make it work with keyup you need to empty the input element again since by that time the value has already been entered in input element
$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$(this).val(''); //<--- this will empty the value in the input.
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
NOTE: However emptying the input does removes the complete value even when there are numbers in it so, I prefer keydown in such cases.
Updated
This is a little hack on input value but (I will still prefer to go with keydown), Use this if you really want keyup to work :). since I am modifying the default browser behaviuor, you might also need to think of lots of other cases here.
$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
if(e.which != 13){ //<--- don't remove when entered is pressed.
$(this).val(e.currentTarget.value.substr(0, e.currentTarget.value.length - 1));
}
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
console.log(e.currentTarget.value);
});
working fiddle

Trying to get numbers from keypress document, javascript

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

Which is the proper way of filtering numeric values for a text field?

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('');
}
});
});

Cancel the keydown in HTML

How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.
If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.
Example code using addEventListener and ignoring ancient version of Opera
document.addEventListener("keydown", function(evt) {
// These days, you might want to use evt.key instead of keyCode
if (/^(13|32|37|38|39|40)$/.test("" + evt.keyCode)) {
evt.preventDefault();
}
}, false);
Original example code from 2010
var cancelKeypress = false;
document.onkeydown = function(evt) {
evt = evt || window.event;
cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
if (cancelKeypress) {
return false;
}
};
/* For pre-Blink Opera */
document.onkeypress = function(evt) {
if (cancelKeypress) {
return false;
}
};
Catch the keydown event and return false. It should be in the lines of:
<script>
document.onkeydown = function(e){
var n = (window.Event) ? e.which : e.keyCode;
if(n==38 || n==40) return false;
}
</script>
(seen here)
The keycodes are defined here
edit: update my answer to work in IE
This is certainly very old thread.
In order to do the magic with IE10 and FireFox 29.0.1 you definitely must do this inside of keypress (not keydown) event listener function:
if (e.preventDefault) e.preventDefault();
jQuery has a nice KeyPress function which allows you to detect a key press, then it should be just a case of detecting the keyvalue and performing an if for the ones you want to ignore.
edit:
for example:
$('#target').keypress(function(event) {
if (event.keyCode == '13') {
return false; // or event.preventDefault();
}
});
Just return false. Beware that on Opera this doesn't work. You might want to use onkeyup instead and check the last entered character and deal with it.
Or better of use JQuery KeyPress
I only develop for IE because my works requires it, so there is my code for numeric field, not a beauty but works just fine
$(document).ready(function () {
$("input[class='numeric-field']").keydown(function (e) {
if (e.shiftKey == 1) {
return false
}
var code = e.which;
var key;
key = String.fromCharCode(code);
//Keyboard numbers
if (code >= 48 && code <= 57) {
return key;
} //Keypad numbers
else if (code >= 96 && code <= 105) {
return key
} //Negative sign
else if (code == 189 || code == 109) {
var inputID = this.id;
var position = document.getElementById(inputID).selectionStart
if (position == 0) {
return key
}
else {
e.preventDefault()
}
}// Decimal point
else if (code == 110 || code == 190) {
var inputID = this.id;
var position = document.getElementById(inputID).selectionStart
if (position == 0) {
e.preventDefault()
}
else {
return key;
}
}// 37 (Left Arrow), 39 (Right Arrow), 8 (Backspace) , 46 (Delete), 36 (Home), 35 (End)
else if (code == 37 || code == 39 || code == 8 || code == 46 || code == 35 || code == 36) {
return key
}
else {
e.preventDefault()
}
});
});

Keyboard navigation with Jquery

In Jquery, how can I set an event such that when user is browsing some pictures, and presses the left/right arrow key, it calls a function which can be used to show the previous/next photos? I only need to know how to check if the key pressed was the right/left arrrow key and ignore all other key preses.
The image will be in its own div.\
I've used this in the past. It works for me in the enviornments I've used (linux and windows with FF)
$(document).keypress( function(e) {
if (e.keyCode === 37) {
// left
}
else if (e.keyCode === 39) {
// right
}
});
That being said, I'm not so sure connecting on the arrow keys is a good idea since a user could change text size and cause the scroll bar to appear. Arrowing would change the picture unexpectedly.
Use the jQuery keypress event like so:
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// backspace in IE only be on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
I'm not sure which value will be present for left/right but a little experimenting with this script should get you going

Categories