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!!!
Related
I want to save page changes when Ctrl-S or Ctrl-Enter is pressed
Ctrl-Enter works fine but on Ctrl-S I cannot prevent a Save dialog to appear.
$(document).on('keydown', function(e){
if (e.ctrlKey && (e.keyCode == 13 || e.keyCOde == 83)){
e.preventDefault();
// save data...
}
});
Any help?
Typo in your code
e.keyCOde == 83 ===> e.keyCode == 83 [Character "O" should be small]
This is what I use :
$(document).keydown(function(event) {
if (!((String.fromCharCode(event.which).toLowerCase() == 's' || event.keyCode == 13) && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Another choice is that you can use Shortcut library, you can enjoy more shortcut keys than just ctrl+s. Plus, this library has short & handy code as well :
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
Basically, the Chromebook I'm using has trouble distinguishing between alt keys. As you can see in the image below, there's one on the bottom left (second key from the left, which I'll refer to as ALT1), and a smaller one on the bottom right (5th key from right, ALT2).
(source: computershopper.com)
My code has this if function, which is triggered by the alt and enter key:
if (e.altKey && e.keyCode == 13) {
When I press ALT1 and the enter key, the function works as intended. However, when I press ALT2 and the enter key, all it does is trigger the 'enter' event (So, if I'm in a form, it would submit the form).
To try to fix this, I tried using
if (e.keyCode == 18 && e.keyCode == 13) {
However, neither ALT1 or ALT2 work with that. Any ideas?
You can test your two alt key code in this page : http://keycode.info/
Maybe the Chromebook is giving a different code for the two alt key.
In real life, simultanius events rarely exist. What i'm saying is that whatever two keys you try to hit the same time, you won't succeed in doing this at EXACTLY the same time.
you can now use this.
var key1pressed = false;
var key2pressed = false;
$("#somelement").keydown(function(e) {
if(e.which == 13) {
key1pressed = true;
}
if(e.which == 18) {
key2pressed = true;
}
keyspressed();
}).keyup(function(e) {
if(e.which == 13) {
key1pressed = false;
}
if(e.which == 18) {
key2pressed = false;
}
});
function keyspressed() {
if(key1pressed == true && key2pressed == true) {
alert("you pressed these 2 keys together");
}
}
I guess this is what you mean?
Update 2
I used a slightly modified version of my original code.
<script>
window.onkeydown = function (e) {
var enter1 = false;
if (e.keyCode == 13) {
var enter1 = true;
}
if (e.key === 'AltGraph') {
if (enter1 = true) {
//Do what Alt + Enter does
console.log("It worked");
}
}
if (e.altKey && e.keyCode == 13) {
//Do what Alt + Enter does
console.log("It worked");
}
};
</script>
This works like a charm: now both ALT1 and ALT2 work.
Original Answer:
By using this code snippet, I was able to figure out the answer.
document.getElementById("ta").addEventListener("keydown", function(e) {
var keyLocation = ["Standard", "Left", "Right", "Numpad", "Mobile", "Joystick"][e.location];
var message = "Key '" + (e.key || e.keyIdentifier || e.keyCode) + "' is down. Location: " + keyLocation;
this.value += "\n" + message;
e.preventDefault();
}, false);
<textarea id="ta" rows="10" cols="50">Click on here and press some modifier keys such as Shift</textarea>
ALT1 registers as 'Alt', while ALT2 shows up as 'AltGraph'. According to Wikipedia, an AltGraph key is:
AltGr (also Alt Graph, Alt Graphic, Alt Graphics, Alt Grammar, Alt Car, or Right Alt[1]) is a modifier key found on some computer keyboards and is primarily used to type characters that are unusual for the locale of the keyboard layout
Knowing this, I could easily modify my original "if" statement from
if (e.altKey && e.keyCode == 13) {
to this
if (e.altKey && e.keyCode == 13 || e.key === 'AltGraph' && e.keyCode == 13) {
However, I ran into a problem, and haven't been able to figure it out.
if (e.key === 'AltGraph') {
works just fine: however, when I try
if (e.key === 'AltGraph' && e.keyCode == 13) {
it doesn't work. I don't know how, and if anyone can figure out, I'll accept their answer instead. However, for the time being, my answer contains the most relevant info for anyone else who had a similar issue.
UPDATE:
I've figured out the error- however, I can't fix it. This code works fine
if (e.shiftKey && e.key === 'AltGraph') {
It's because I used e.shiftKey instead of e.keycode == 'shift key code'.
However, enter doesn't have the equivalent of this. Using the 'template' below, it works for Shift, Ctrl, and Alt- however, not for enter. Any ideas?
event.[key]Key
For reference, I used these questions to find the answer
Is there a way to detect which side the Alt key was pressed on (right or left)?
Detect Alt Gr (Alt Graph) modifier on key press
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.
I am doing validation on an input type='text' element. I have wired up the 'paste' and the 'keydown' events to trap the input and restrict it to just numbers. The keydown seems to work without a hitch, however, I could not seem to get any of the browsers to actually NOT PASTE the text into the field (I see that there is a beforepaste event, which may be the ticket -- however it appears to not be supported by firefox. In the end, I resulted to just blanking out the input if the value was not a number. This causes a momentary flicker, but seems to work.
Is there a cleaner way to do this? Am I missing something? Is there anyway to prevent the flicker? I know the HTML5 has a type='number', but I'm not ready to go there yet.
<input type="text" id="number" />
<script type="text/javascript">
$(document).ready(function () {
enableNumericOnlyEntry("#number");
function enableNumericOnlyEntry(object) {
$(object).bind('paste', numericOnlyPaste);
$(object).bind('keydown', null, numericOnlyKeyDown);
function numericOnlyPaste(event) {
var inputText = "";
var element = event.target;
setTimeout(function () {
var text = $(element).val();
if (isNaN(text)) {
$(element).val("")
return false;
}
}, 0);
}
function numericOnlyKeyDown(event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A/a
(event.keyCode == 65 || event.keyCode == 97) && (event.ctrlKey === true) ||
// Allow: Ctrl+C/c
(event.keyCode == 67 || event.keyCode == 99) && (event.ctrlKey === true) ||
// Allow: Ctrl+V/v
(event.keyCode == 86 || event.keyCode == 118) && (event.ctrlKey === true) ||
// Allow: Ctrl+X/x
(event.keyCode == 88 || event.keyCode == 120) && (event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return true;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
return false;
}
}
}
}
});
I've used this project to create a field that is a masked edit box, you could remove the underscore to it also so it doesn't look like a masked edit. Really easy to use: http://digitalbush.com/projects/masked-input-plugin/
then you'd use something like $("#box").mask("9999999"); and your good to go, works great!
HTML5's <input type="number"> is really where you want to go with this. If you're working with browsers that support it (basically everything except Safari and old versions of IE), it does everything you want.
That said, why not register an onpaste handler so you can reduce pasted content to just numbers after the user pastes?
In Jquery, how can I set an event such that when user is browsing some pictures, and presses the left/right arrow key, it calls a function which can be used to show the previous/next photos? I only need to know how to check if the key pressed was the right/left arrrow key and ignore all other key preses.
The image will be in its own div.\
I've used this in the past. It works for me in the enviornments I've used (linux and windows with FF)
$(document).keypress( function(e) {
if (e.keyCode === 37) {
// left
}
else if (e.keyCode === 39) {
// right
}
});
That being said, I'm not so sure connecting on the arrow keys is a good idea since a user could change text size and cause the scroll bar to appear. Arrowing would change the picture unexpectedly.
Use the jQuery keypress event like so:
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// backspace in IE only be on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
I'm not sure which value will be present for left/right but a little experimenting with this script should get you going