Firefox - keypress bug. Can't use backspace with only letter input script - javascript

I've an input box that I only want to allow letters, hyphen, space and backspace. All is good on chrome but on Firefox backspace (or charcode 8) does not work. - https://jsfiddle.net/npo7y7fr/
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) return false;
});
});
I've tried adding && (key.charCode != 8) also changes keypress to others like 'keydown, keyup' etc...
Can anybody get this working in Firefox (40.0.3) or something that I can use instead?

Since Space will send keycode 32 and backspace will send 0 in Mozilla so that's why it is not working in mozilla.
change your script as below
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45) && (key.charCode != 32) && (key.charCode != 0) ) return false;
});
});
hope this helps..!!

Instead of hardcoding some special keys, just skip the filtering for all of them. With the accepted solution, you still cancel arrow keys, Home, End, etc., which is a bad thing for the user.
As all special keys have a key field longer than 1 character, you can safely do this:
$(document).ready(function () {
$('.textInput').keypress(function (event) {
return event.key.length > 1 || event.ctrlKey || !!event.key.match(/[a-zA-Z \-]/);
});
});
The pressed key is accepted if it's a special key, it's been pressed simultaneously with the Ctrl key (to allow copying and pasting) or if it matches the regular expression (letters, space and hyphen).
As the user can paste invalid content, you should still remove illegal characters with the oninput event (probably something like ctrl.value.replace(/[^a-zA-Z \-]+/g, '')).

Rather than trying to control what the browser can enter into the input, it might be easier to just filter the contents of the textbox on keyup.
Consider the following:
$('.textInput').keyup(function() {
$(this).val( $(this).val().replace(/[^a-zA-Z]/,''));
});
Hope this helps.

Related

jquery keydown bind with regex does not validate for apostrophe and periods

I have been using jquery to capture the keydown event and validate the entered text for different cases like: characters only, alpha-numeric, characters and spaces etc.
Regex used:
Characters with spaces: ^[a-zA-Z ]+$
Characters only: ^[a-zA-Z]+$
Alphanumerics: ^[a-zA-Z0-9]+$
This is how I am using the bind function:
$('.chars_and_space_only').bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
All of above uses cases are working fine, however I have to now include characters, spaces, apostrophe and periods. So this is the method I have modified:
$(".chars_space_dots_apostrophes_only").bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z '.]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
This, strangely doesn't seem to work. Here is the fiddle: https://jsfiddle.net/ugu8f4y3/
Regex used: ^[a-zA-Z '.]+$
Regex validator does validate this text for the above regex:
Hello. World's
But the text field in fiddle does not allow me to enter periods and apostrophes, is there something I am missing here?
The problem is with jquery and the keydown event. Replace it with keypress and you'll be good to go. You should also only need to check in which.
keydown and keyup are important for cases when you're concerned with the position of the key's physical location. In this case you want to know that the key was depressed and handle the resulting input. jquery will normalize the character codes differently.
Further information about the differences between keypress, keydown and key up.
Updated Fiddle

how to prevent "post accent" in input text

I believe this is an easy one, but I couldn't find any answer after a couple of hours searching on google (maybe I wasn't able to use the correct words in the search :-P)
I have a javascript method that prevents the user to fill the textbox with other characters than numbers, as it can be seen in the code below, and it's used in KeyDown event:
function checkNumberInput(e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
The problem is that, if the user types accent characters that "waits" a second key (such as ~´`^), it appears in the textbox when a number is typed right after.
For example:
a) types 1 => [1________]
b) types ~ => [1________]
c) types 3 => [1~3______]
How can I prevent this from happening? Thanks in advance.
Do you mean that ' and a are converted to а́?
This is built in the system, you cannot change that.
What you can do is check the input after that. This way you'll also prevent paste with mouse:
$('input').on('keydown', checkNumberInput).on('blur focus', function(){
var val = $('input').val();
// now remove everything that is not allowed
val = val.replace(/[^0-9.]+/g, '');
$('input').val(val);
})
(The exact implementation is deffinitely not perfect, just to illustrate what's going on)
https://jsfiddle.net/5afwdhzx/
About really instant fix - give this closure a name and call it inside the keyDown function with some short delay, like #haroldo said above.
https://jsfiddle.net/5afwdhzx/1/

how to read two or more digit inputs from a BARCODE

I am developing a website and I want to read the input from the bar code.
While I am getting the input from bar code keyboard input should not be considered as a input since when I am trying to get the integer inputs key board is giving inputs.
below is the code which I tried with:
$(document).keydown(function(e) {
if (e.altKey & (e.which > 47 && e.which < 58)) {
var value = "";
value += String.fromCharCode(e.which);
window.location = "../../patient_overview_c/view/" + value;
}
});
I want to get the input while I am pressing the alt key. I have done this for only one digit vale. I want to go for two or more digits.
You are having one ampersand instead of two, on your second line. The e.altKey returns a bool.
Change
if (e.altKey & (e.which > 47 && e.which < 58)) {
^
into
if (e.altKey && (e.which > 47 && e.which < 58)) {
^

Trying to validate a function in HTML

For my html, I'm trying to validate a form with a postcode input.
But this input is not working (or not being recognized). For my postcode input, I want to text box to only accept numbers.
Postcode input:
var Postcode = document.forms["Rego"]["postcode"].value;
var e = Postcode;
var code = e.keyCode;
if (code > 47 && code < 58) || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
return false;
What am I doing wrong?
In your condition if in line 4 after 58 why you close the ) ???
You are doing quite a few things wrong. You are not setting an event handler, you are actually binding to the value in the input box. You have to first get the DOM element representing the text box, then bind an event handler to the DOM element. Try this:
var Postcode = document.getElementById('post');
Postcode.onclick = function(e) {
console.log(e);
var code = e.keyCode;
if (code > 47 && code < 58 || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
e.preventDefault()
return false;
}
Fiddle: http://jsfiddle.net/S47gV/
To only accept numbers, you can use (for HTML5):
<input type="number" name="whatever">
Plus, if you want to validate it with js (doing so in browser is not recommended as anyone can modify your js file and push the contents to the server) or server code, here's some insight:
Try to convert the string passed to the server into a number. For example, in python you can do: int(whatever). If the conversion fails, that means the string isn't a number.
Hope that helps :)
If you use HTML5 you can set this automatically.
<input type="number" name="quantity" min="47" max="58">
By using below code textbox/inputbox allow only numeric value
$j('#inputbox_id').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
e.preventDefault();
}
}
});
and if you want to set length of textbox/input box then set "maxlength=5"
I think i have found what you are doing wrong:
You are reading postcode value from input type and then comparing its keycode.
However‚ it may work only when your input has single number and when you type more characters in it your postcode variable becomes something for example 5436 and then when you use keycode function on this in wont work as expected.

How to know if .keyup() is a character key (jQuery)

How to know if .keyup() is a character key (jQuery)
$("input").keyup(function() {
if (key is a character) { //such as a b A b c 5 3 2 $ # ^ ! ^ * # ...etc not enter key or shift or Esc or space ...etc
/* Do stuff */
}
});
You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.
The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.
$("input").keypress(function(e) {
if (e.which !== 0) {
alert("Charcter was typed. It was: " + String.fromCharCode(e.which));
}
});
keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.
Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):
You can't do this reliably with the keyup event. If you want to know
something about the character that was typed, you have to use the
keypress event instead.
The following example will work all the time in most browsers but
there are some edge cases that you should be aware of. For what is in
my view the definitive guide on this, see
http://unixpapa.com/js/key.html.
$("input").keypress(function(e) {
if (e.which !== 0) {
alert("Character was typed. It was: " + String.fromCharCode(e.which));
}
});
keyup and keydown give you information about the physical key that
was pressed. On standard US/UK keyboards in their standard layouts, it
looks like there is a correlation between the keyCode property of
these events and the character they represent. However, this is not
reliable: different keyboard layouts will have different mappings.
The following was the original answer, but is not correct and may not work reliably in all situations.
To match the keycode with a word character (eg., a would match. space would not)
$("input").keyup(function(event)
{
var c= String.fromCharCode(event.keyCode);
var isWordcharacter = c.match(/\w/);
});
Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.
I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.
Using keyPress with event.which is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl).
Using keyDown (as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode with String.fromCharCode() (keyCode and charCode are not the same!).
However, what we DO have with the keydown or keyup event is the actual key that was pressed (event.key).
As far as I can tell, any key with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!
Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.
So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup or keydown will work here, but keypress will not)
$("input").keydown(function(event) {
var isWordCharacter = event.key.length === 1;
var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;
if (isWordCharacter || isBackspaceOrDelete) {
// do something
}
});
This helped for me:
$("#input").keyup(function(event) {
//use keyup instead keypress because:
//- keypress will not work on backspace and delete
//- keypress is called before the character is added to the textfield (at least in google chrome)
var searchText = $.trim($("#input").val());
var c= String.fromCharCode(event.keyCode);
var isWordCharacter = c.match(/\w/);
var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);
// trigger only on word characters, backspace or delete and an entry size of at least 3 characters
if((isWordCharacter || isBackspaceOrDelete) && searchText.length > 2)
{ ...
If you only need to exclude out enter, escape and spacebar keys, you can do the following:
$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
alert('test');
}
});
See it actions here.
You can refer to the complete list of keycode here for your further modification.
I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.
(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)
Edit: rewrote it as a jQuery plugin.
(function($) {
$.fn.normalkeypress = function(onNormal, onSpecial) {
this.bind('keydown keypress keyup', (function() {
var keyDown = {}, // keep track of which buttons have been pressed
lastKeyDown;
return function(event) {
if (event.type == 'keydown') {
keyDown[lastKeyDown = event.keyCode] = false;
return;
}
if (event.type == 'keypress') {
keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
return;
}
// 'keyup' event
var keyPress = keyDown[event.keyCode];
if ( keyPress &&
( ( ( keyPress.which >= 32 // not a control character
//|| keyPress.which == 8 || // \b
//|| keyPress.which == 9 || // \t
//|| keyPress.which == 10 || // \n
//|| keyPress.which == 13 // \r
) &&
!( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
!( keyPress.which == 63273 ) && //
!( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
!( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
( keyPress.which == 35 || // End
keyPress.which == 36 || // Home
keyPress.which == 45 || // Insert
keyPress.which == 46 || // Delete
keyPress.which == 144 // Num Lock
)
)
) ||
keyPress.which === undefined // normal character in IE < 9.0
) &&
keyPress.charCode !== 0 // not special character in Konqueror 4.3
) {
// Normal character
if (onNormal) onNormal.call(this, keyPress, event);
} else {
// Special character
if (onSpecial) onSpecial.call(this, event);
}
delete keyDown[event.keyCode];
};
})());
};
})(jQuery);
I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters
$('#input').on('keyup', function() {
var words = $(this).val();
// if input is empty, remove the word count data and return
if(!words.length) {
$(this).removeData('wcount');
return true;
}
// if word count data equals the count of the input, return
if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){
return true;
}
// update or initialize the word count data
$(this).data('wcount', words.length);
console.log('user tiped ' + words);
// do you stuff...
});
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="input" id="input">
</body>
</html>

Categories

Resources