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

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

Related

KeyCode is taking wrong in mozilla

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

If keycode && input are not empty do something

I have barcode input in which I enter barcodes multiple times, every time I add barcode, barcode is added to the list even if I only press enter with empty value.
I want to start function only if user press enter key == 13 and value is not empty.
This is code:
if(key == 13) {}
I tried but without success:
var value = $("#barcode").val();
if(key == 13 && value.length > 0)
{alert("This works!")}...
You need to run your code under either the keyup or keypress event. Assuming you use jQuery to attach the event, you should also use the which property of the provided event object to get the keycode. Try this:
$('#barcode').keypress(function(e) {
if (e.which == 13 && this.value) {
alert("This works!")
}
})
Working example

Javascript Validation on Control-V for the Textbox

I have to validate the textbox to enter only alpha numeric characters.
The function validateAlphaNumeric(evt, txtbox) fires onkeypress event on textbox.
Below is the function written in Javascript.
But I am not able to get the value of the textbox if I do Ctrl+V. I need to validate if user pastes.
Can any one suggest me on this?
function validateAlphaNumeric(evt, textBox) {
/* File Description : Numbers,Characters,Hyphen(-),Slash(/)and Space */
var charCode;
charCode = (evt.which) ? evt.which : window.event.keyCode;
if (charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode == 8 || charCode >= 48 && charCode <= 57 || charCode == 45) {
return true;
}
else {
var errorMsg = document.getElementById(textBox.id + 'Error');
if (errorMsg != null) {
errorMsg.innerText = "Please Enter Alpha – Numeric Characters only";
}
return false;
}
}
I have found an answer:
Try this on onpaste event.
Surely will work out.
I tried this:
function onPaste(evt, textBox) {
pastedText = window.clipboardData.getData('Text');
if (pastedText matches regExp) {
return true;
} else {
//display error msg
return false;
}
}
Regards..
validate text box on onblur() event of that TextBox. your problem will sure get solved.
from html5 on there is the oninputevent which does exactly what you want.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput
In the handler, check that the value property of the text box contains only allowed characters.
Note that IE9 has buggy support for this event - basically it doesn't recognize character deletion, but it doesn't affect you because you can't make the text invalid just by removing stuff. See here for more detail:
http://help.dottoro.com/ljhxklln.php
If you can't use oninput because you really need to support IE8-IE7 (hint: you don't really want to) you can instead fix your code by listening to the onpaste event too to get text paste events.

Selecting text on-the-fly from textbox leaves out last character in javascript

I'm trying to get the text from a textbox as a user types, so that I can parse it and display information accordingly as the user enters a command. However, it seems as though the function I'm writing is getting the text from the box before the letter is entered into the text box. How do I prevent the function from grabbing the content from the textbox before the typed character is entered? I considered grabbing the id of the key and altering the inputted string accordingly, but I feel like there should be a better way.
The code:
$('#inputConsoleForm').keydown(function(event){
//Get key code
var code = (event.keyCode ? event.keyCode : event.which);
//Get console text (doesn't behave as expected)
var consoleCommand = document.inputConsoleForm.console.value;
function parseConsoleCommand(consoleCommand) {
/* Returns true if command is valid*/
}
if(code === 13) {
event.preventDefault();
if(!parseConsoleCommand(consoleCommand))
alert("INVALID COMMAND LINE");
else
attemptExecute();//Runs the command
}
if(code === 32 || (code >= 48 && code <= 123) || code === 61 || code === 109 || code === 188 || code === 8) {
if(parseConsoleCommand(consoleCommand)){
$(document.inputConsoleForm.console).css("background-color", "#FFDFDF");
}
else{
$(document.inputConsoleForm.console).css("background-color", "");
}
}
});
You could use the HTML5 input event (falling back to the propertychange event in IE < 9). Here are two answers detailing how to do this:
jQuery keyboard events
Catch only keypresses that change input?
Use "change" for best results I'd say. You could continue to use keydown (or keyup) but you'll have to fetch the key being pressed from the event object and append it to the text string.

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

Categories