Number field that deletes non-numbers without clearing previous numbers? - javascript

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

Related

Logic validate angular, javascript

<input onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : (!isNaN(Number(event.key)) [(ngModel)]="pageInput"/>
I have input that validates the value when the user enters data, my current logic of onkeydown above is not allowing the user to write down non-numeric characters!
Here is the code which I validate (!isNaN(Number(event.key))
Could you guys help me to add more logic to this (!isNaN(Number(event.key))
I have {{totalpages}} that I want User just only write down only the number which > 0 and >= {{totalpages}}
handle the keydown event in angular like this:
(keydown)="onKeyDown($event)"
then put this in your ts controller:
onKeyDown(event) {
// whatever keydown logic you would like in here
}

Numbers-only JavaScript Firefox solution

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">

Altering the keypress event of certain keys in JavaScript

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.

including two functions in a javascript keypress

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

Only-numerics in Input

I currently have a snippet that only allows numbers to be typed into an input:
$('input').bind('keypress', function(event) {
var charCode = event.which;
var keyChar = String.fromCharCode(charCode);
return /[0-9]/.test(keyChar);
});
jsFiddle: http://jsfiddle.net/wgsPr/
How can I adjust this to prevent typing in numbers greater than 500?
For example, if a user types 50, then types a 1 after, it won't display the 1. However if the user types a 0 after, it will display 500. And the same goes for if a user tries to type 968 it will not show the 8, it will only show 96.
Hopefully this makes sense.
The line would be
return /\d/.test(keyChar) && parseInt(this.value+keyChar, 10) <= 500;
(Demo)
However, I still suggest not to hook on and preventDefault of keypress events - go for keyup and change events and show error messages if the input's value is invalid. Or use a HTML5 <input type="number" /> with min and max attributes.
You really should not use such methods. This works far better:
<input type="number" min="0" max="500" />
However, if you insist, take your existing code and replace the return line with:
return /\d/.test(keyChar) && this.value <= 500;
if ($(this).val() > 500) {
$(this).val($(this).val().substr(0, $(this).val().length - 1));
return false;
}
I went ahead and attempted to solve this myself, which works. Basically, it checks the value and remove the last character in the case that it makes the entire input value larger than 500. Please let me know if anything should be modified.

Categories

Resources