Only numbers in input : detect "capsLock" on keypress - javascript

I made a function to prevent a user from entering anything other than numbers into a field (but allows useful keys like "backspace", "enter", etc ...)
Here a jsFiddle for the example: http://jsfiddle.net/cWHRp/1/
And the javascript code:
$('input').on('keypress', function (e) {
if (
// Allow "backspace", "tab", "enter", "escape" and "delete"
($.inArray(e.keyCode, [8, 9, 13, 27, 46]) !== -1) ||
// Allow "shift + decimal point" (= delete on numpad)
(e.shiftKey === true && e.keyCode == 110) ||
// Allow "Ctrl + A" and "Ctrl + C"
(e.ctrlKey === true && ($.inArray(e.keyCode, [65, 67]) !== -1)) ||
// Allow "end", "home", "left arrow", "up arrow", "right arrow" and "down arrow"
(e.keyCode >= 35 && e.keyCode <= 39) ||
// Allow "shift + classic numbers"
(e.shiftKey === true && e.keyCode >= 48 && e.keyCode <= 57) ||
// Allow numbers on numpad
(e.keyCode >= 96 && e.keyCode <= 105)
) {
return;
}
e.preventDefault();
});
It works well, even with shift + number. But I don't know how to detect that capsLock is ON when the user is typing on the keyboard.
Have you any idea to solve this problem please?
Thank you in advance!

Don't do this, this creates more problem than it solves. Here are some better solutions:
a) <input type="number" />
b) <input type="text" pattern="\d+" />
c) .replace(/[^\d]/g,'') in a change (or keyup) event listener
d) masked-input plugins
e) client + server-side validation (which you should use anyway)

OK, so first off as others have mentioned: why are you doing this?. #pawel has suggested some better approaches.
That said, using the KeyboardEvent.getModifierState() method, you can do the following:
$('input').on('keypress', function(e) {
var isCapsLock = e.originalEvent.getModifierState("CapsLock");
...
});

You could use oninput event (taking care of paste value from contextmenu) and just use a regex to match all not numeric characters:
SEE DEMO
$('input').on('input', function (e) {
this.value = this.value.replace(/\D/g,'');
});
You could still use onkeyup/onpaste event instead, for older browsers which don't support oninput event.

Related

only allow numbers in contenteditable elements?

How can I make contenteditable elements only allow entry of numeric values?
I tried to use something like:
onkeypress='return event.charCode >= 48 && event.charCode <= 57'
...on elements that are contenteditable, but it still allows entry of alphabetic characters.
Thanks!
Why not just use an input?
<input type="number">
If you still want to use contenteditable, you can add an event listener like so:
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
This will block all characters that are not numbers (0-9)
Salaam
This will allow only numbers
$('[contenteditable="true"]').keypress(function(e) {
var x = event.charCode || event.keyCode;
if (isNaN(String.fromCharCode(e.which)) && x!=46 || x===32 || x===13 || (x===46 && event.currentTarget.innerText.includes('.'))) e.preventDefault();
});
I have also tested decimals. There are three major conditions to get allowed
Is a Number and Not delete button
Not Space
Not Enter Button
Allow Decimal point only once
Let me know if you face any bug in comments
Thank you
If you want to enter only 0-9 in contenteditable div then you can use this code. This code also prevent user to copy paste into the field
<div contenteditable id="myeditablediv" oncopy="return false" oncut="return false" onpaste="return false">10</div>
Javascript
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
if you want to enter decimal points instead of a number then you can use this javascript code
$("#myeditablediv").keypress(function(e) {
var x = event.charCode || event.keyCode;
if (isNaN(String.fromCharCode(e.which)) && x!=46) e.preventDefault();
});
Allowing numbers, the point, the backtracking
<div
on:keydown={(event) => {
if (
event.code.includes('Digit') ||
event.code === 'Backspace' ||
event.code === 'Period'
) {
console.log(e)
} else {
event.preventDefault()
}
}}
>
foo
</div>
If you want to allow only numbers, you can use :
if (e.which < 48 || e.which > 57) e.preventDefault();
If you want to enable pad numbers, use this code :
if (!e.key.match(/^[0-9]/g) && e.keyCode !== 8 && e.keyCode !== 46) {
e.preventDefault();
}
The regex starts with '^' to prevent F5 to works for example. We add e.keycode 8 and 46 to avoid the prevent default on backspace/delete
This method doesn't allow decimals, you'll need to modify regex for it
Just expanding on ElChino3312's answer to include some additional accepted keys (numpad, arrows and delete) and excludes period as I'm not allowing decimals in my case:
if (!(event.code.includes('Digit') || event.code.includes('Numpad')
|| event.code === 'ArrowLeft' || event.code === 'ArrowRight'
|| event.code === 'Backspace' || event.code === 'Delete'))
{
event.preventDefault()
}

JavaScript - Prevent "CTRL" and "ALT" being used for special characters

With the code below, is there anyway of preventing the user from entering special characters that are generated by pressing CTRL + ALT + 4 for example?
That produces the euro currency sign. All the below code works perfectly, I just need to prevent any special characters that are generated from CTRL + ALT
Prevent the user from using their mouse to right click and paste the content in
Working with IE8
`
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// 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();
}
});`
If you want to allow only certain keyboard shorcuts, you can disable anything but whatever you let pass. You can also decide to list everything that you want disabled, and allow everything else to execute. A simple way I see this can go is to disable the Ctrl key and the Alt key if they are pressed simultaneously, as such:
$("#txtboxToFilter").keydown(function (e) {
if (e.ctrlKey === true && e.altKey === true) {
return;
}
else {
//Do whatever;
if (e.key === "Tab") {
//Tab was pressed
}
else if (e.key === "H") {
//Shift H was pressed
}
else if (["Home", "End", "PageUp", "PageDown"].includes(e.key) === true) {
//Navigational Keys Were Pressed
}
else if (["ArrowUp", "ArrowDown", "ArrowRight", "ArrowLeft"].includes(e.key) === true) {
//Directional Arrows Were Pressed
}
}
});
And may I recommend that you use e.key instead of e.keyCode, e.which, or code, because it is more supported, and it is way easier to understand. Just take a look at the code snippet above, there are examples of e.key. Besides, there is no confusion with numbers, because the key names are used. If you wanted to use the Windows Key on Windows, the Search key on Chromebooks, e.key === "Meta" is the way to go.
Hope this extra information helps!!!

How to capture ALT+C keypress

I want catch an event for Alt+c or something like that. My code is
html
<input type="text" id="name"/>
JavaScript
$("#name").keydown(function(e) {
if(e.keyCode == 67 && e.keyCode == 18){alert(e.keyCode);}
});
where is the problem? How it works on both Chrome & firefox?
You need to check for e.altKey instead:
if(e.altKey && e.keyCode == 67){alert(e.keyCode);}
Basically, you are checking for two codes as the same time. The event (e) has several values you can work with ... including altKey which is a boolean (true or false) ...
Try ... watching the e.altKey and the e.keyCode values.
$("#name").keydown(function(e) {
if(e.altKey && e.keyCode == 67) {
alert(e.keyCode);
}
});
With the right version of jQuery, there should be no issue between browsers.
$(document).keydown(function(e) {
//console.log(e.keyCode); If you want to check other keys code
if(e.keyCode == 67 || e.keyCode == 18){
console.log("alt or c pressed");
}
});
You can work around this to check if the two keys are pressed at the same time. I sujest you to use an aux var set to zero wich increase his value when keydown event triggered and decrease it when keyup.

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

Categories