As a standard feature I keep a "don't allow returns" on form text fields using:
keypress="return event.keyCode != 13"
However I need to also only allow a numeric value in some field items using:
keypress="return inputLimiter(event,'Numbers')"
which ties in with a function.
So I need to tie the two together in the same keypress but can't find anything on if this is possible and when I've tried combining them neither work.
Combine them with &&.
Using the same style syntax as you used in the question:
keypress="return event.keyCode != 13 && inputLimiter(event,'Numbers')"
In "real" JS:
window.onkeypress = function(){
return event.keyCode != 13 && inputLimiter(event,'Numbers');
};
Related
I need some help cleaning up a popular piece of vanilla JavaScript code that causes issues in Firefox.
The following which/keyCode check seems to be about the most popular vanilla JS solution to allow only numbers into an input or textarea.
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode > 31 && ( charCode < 48 || charCode > 57)) {
return false;
}
return true;
Called via onkeypress="return function(event);" on the tag.
However, Firefox apparently binds arrow keys to onkeypress calls, rather than just to onkeyup and onkeydown like other browsers. This means that e.g. the left arrow key's charCode is 37, but so is the charCode for % (shift+5). Even more importantly, it means that the arrow keys can't be used for navigation (moving the caret/text cursor left or right).
However, the difference is that the left arrow key has keyCode 37, while % has the charCode and which of 37 (as shown on http://www.asquare.net/javascript/tests/KeyCode.html). So I was able to make the arrow keys work just fine by doing the following:
if (charcode > 31 && (charcode < 48 || charcode > 57)) {
if (e.keycode && e.keyCode > 36 && e.keyCode < 41) {
return true;
}
return false;
}
return true;
However, I feel like this is not the best or cleanest way to do it, and that there might be more keys handled differently by Firefox than just the arrow keys. What would be a cleaner vanilla JS solution or way to check for at least the arrow keys within this function?
Many thanks!
EDIT: I just figured that even though the code solves it for Firefox, it introduces a new problem for all other browsers, in that these now allow charCodes 37-40 (i.e. %) to be entered. Seems that instead of checking the keyCode, it would need to check the charCode or which, in otherwise the same manner.
I would advise against blocking certain keys, as I feel it degrades the user experience. But given that this is what you need, I would suggest to not rely on the keyCode property. Not only are there compatibility problems related to it, it also does not cover all ways input can be made, like with the mouse and context menu, and is deprecated:
This feature has been removed from the Web standards.
The KeyboardEvent.keyCode read-only property represents a system and implementation dependent numerical code
Instead I propose to use the input event, which triggers on every change to the input value, and then to clean the value of non-digits, while putting the cursor at the place where the first offending character was found. This gives about the same user-experience, and has no bad effect on how arrow keys, backspace, delete, selection, ... etc work:
document.querySelector('#num').addEventListener('input', function() {
var badCharPos = this.value.search(/\D/);
if (badCharPos == -1) return; // all OK
// remove offending characters:
this.value = this.value.replace(/\D/g, '');
this.setSelectionRange(badCharPos, badCharPos);
});
<input id="num">
I am working on a project which shows the character code of each key that is pressed down inside a text box.
My problem is that when certain keys, namely: Shift, Backspace, Space are pressed down, their character codes appear like: 16, 8, 32.
I want these keys to retain their normal behavior when pressed. So that space causes a space in the text box, and backspace deletes the character, and so on...but the rest of the keys to continue outputting their character code.
How can I go about accomplishing this?
You can just check for the keys and handle accordingly. Here's a demo:
document.getElementById("test-textbox").addEventListener("keypress", function(event) {
var code = event.keyCode || event.which;
if(code === 16 || code === 8 || code === 32) //check if space, shift, or backspace
return; //if yes, allow
console.log(code); //if not, log value
event.preventDefault(); //prevent entry
});
<input type="text" id="test-textbox">
This will allow the shift, backspace, and space keys to be pressed, but all others will be logged.
I think this will work for you.
var elementID = document.getElementById('elementID');
elementID.onkeydown = function(event) {
var key = event.keyCode || event.charCode;
if( key == 32 || key == 8 )
event.preventDefault();
};
As long as you…
don’t call the preventDefault method on the event object, and
don’t return false from the event handler
…you should be fine.
In particular, the handler…
function showCharCode(event) {
// NOTE: Don’t call `event.preventDefault()` here.
document.querySelector('.char-code').textContent = event.charCode;
// NOTE: Don't return false here.
}
… will still propagate the event to the default textbox (or input, or contenteditable) element.
I am using:
<input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')">
I use it to prevent the user from entering anything except a number into a field on my page. However, I noticed that if the user types a number first but then accidentally hits a non-number key, the field is cleared and they have to start over. This may cause frustration so I was wondering if there was a way to tweak the code so that it does not do this, or if there was a similar method I could use. I am limited to JavaScript, JQuery, and HTML. Any help would be appreciated! :)
I found a solution for my issue. I got rid of the code above and ended up using a JS function. I put in within my $(Document).ready(function() I hope this helps someone with the same problem!
$("#medianSalary").keydown( function(event) { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault();} }); });
I am working on a function to limit the number of chars. a user is allowed to type inside an input text field.
This is it:
$.fn.restringLength = function (id, maxLen) {
$(id).keypress(function(e){
var kCode = e.keyCode ? e.keyCode : e.which,
len = $(id).val().length;
if (kCode != 8 && kCode != 46) {
if (len > maxLen) e.preventDefault();
}
});
}
The function binds the keypress event and gets the code of the pushed key.
If the char. limit is reached, it allows only the delete and backspace keys to be pushed.
What it needs to work great, is a way to bind the "onselect" event in order to have the following behavior:
when the user selects the whole text with the mouse, and types a letter or a number, the whole text gets deleted and that letter appears.
This is something that most of us do when we want to replace some text with another, and I'd like my function to enable this.
Any ideas how?
If i may add something,
Your solution use keypress event, so the event is triggered before the new value of input is computed. That's why you have to check for special key like backspace , enter ... theses do not just add a character to the string so they require special treatment.
For this kind of processing, it's more convinient to have the handler triggered after the string computation. In that way, you can access the input value and modify it if it's not correct.
Unfortunately jquery does not support this event but you can use it with vanilla javascript method.
$(id)[0] // get the vanilla js element
.oninput = function(e){
this.value = this.value.substr( 0 , 10 ) // this.value contain the string after the key press processing
}
function onlyNumeric() {
if (event.keyCode < 48 || event.keyCode > 57) {
event.returnValue = false;
}
}
onkeypress=onlyNumneric();
In IE, this code is working fine. However, in Mozilla Firefox, the event is an undefined error.
In FF/Mozilla the event is passed to your event handler as a parameter. Use something like the following to get around the missing event argument in IE.
function onlyNumeric(e)
{
if (!e) {
e = window.event;
}
...
}
You'll find that there are some other differences between the two as well. This link has some information on how to detect which key is pressed in a cross-browser way.
Or quite simply, name the parameter event and it will work in all browsers. Here is a jQueryish example:
$('#' + _aYearBindFlds[i]).on('keyup', function(event) {
if(! ignoreKey({szKeyCodeList: gvk_kcToIgnore, nKeyCode: event.keyCode })) this.value = this.value.replace(/\D/g, '');
});
This example allows digits only to be entered for year fields (inside a for each loop selector) where ingoreKey() takes a keyCode list/array and compares the event keyCode and determines if it should be ignored before firing the bind event.
Keys I typically ingore for masks/other are arrow, backspace, tabs, depending on context/desired behaviour.
You can also typically use event.which instead of event.keyCode in most browsers, at least when you are using jQuery which depends on event.which to normalize the key and mouse events.
I don't know for sure what happens under the covers in the js engines, but it seems Mozilla FF respects a stricter scope, wherein, other browsers may be automatically addressing the window.event.keyCode scope on their own when the event is not explicitly passed in to a function or closure.
In FF, you can also address the event by window.event (as shown in some examples here) which would support this thought.
Some browsers may not support keyCode you have to use keyChar
function onlyNumeric() {
var chars = event.keyCode | event.keyChar;
if (chars < 48 || chars > 57) {
event.returnValue = false;
}
}
onkeypress=onlyNumneric();