I'm trying to prevent users from entering < or > into my form fields using JavaScript. Here's what I have so far:
$(document).on('keydown', function (e) {
regex = new RegExp("\<|>");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
It's still allowing those characters, how do I stop this?
Why bother translating then regexing? I like to keep it simple:
$(document).on('keypress', function (e) {
if ((e.which == 62) || (e.which == 60)) { // greater than or less than key pressed
e.preventDefault();
}
});
Edit to add:
Alternate if condition based on #Samsquanch feedback:
if ((String.fromCharCode(e.which) == '>') || (String.fromCharCode(e.which) == '<')) { // greater than or less than key pressed
Two things worth noting:
keypress isn't fully supported for all keys across all browsers. You should use keydown or keyup
the < and > key code vary across OS' and keyboard layouts. Hard coding the keycodes won't consistently work
For a cross-OS and cross-keyboard-layout solution (although not as clean), you can do this:
$(document).on('keyup', 'input, textarea', function (e) {
regex = new RegExp("\<|>");
var val = $(this).val();
$(this).val(val.replace(regex, ''));
});
This strips the < and > keys from the input on keyup. The user will see this happening, but it should always catch the desired keys and strip them.
Related
I want to check if the Tab key is pressed and held down and released so that I can perform some other actions with other key combinations.
var shifted = false;
var tabbed = false;
$(document).on('keyup keydown', function(e) {
shifted = e.shiftKey;
tabbed = e.keyCode === 9;
console.log(tabbed);
});
The above code is working fine for the Shift key, but it's not working for the Tab key. When the Tab key is pressed and held the tabbed variable should be true and when released it should be false.
To answer the question (rather than question if the question should be a question):
This MDN page describes how keyboard events work.
one keydown, with repeat = false
multiple keydown, with repeat = true
one keyup
So you can check for when the tab is started to be held down with keydown && !repeat and when it's stopped being held down with keyup
Note you must also cancel the event so that it doesn't do the correct/expected behaviour of tabbing to the next tabbed-indexed input (emphasis on what tab actually should be doing...)
It's also cleaner to keep the events separate, giving:
var tabdown = false;
$(document).on('keydown', function(e) {
if (e.keyCode === 9) {
tabdown = true;
return false;
}
if (tabdown && e.keyCode >= 49 && e.keyCode <= 51)
{
$("#in" + (e.keyCode-48)).focus();
return false;
}
});
$(document).on('keyup', function(e) {
if (e.keyCode === 9) tabdown = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<em>hold tab and 1, 2 or 3 to change inputs</em><br/>
<input type='text' id='in1'>
<input type='text' id='in2'>
<input type='text' id='in3'>
But you'll note that an instruction is needed on the page as it's not a normal method - and also disables the normal method to easily/quickly switch between inputs in order.
This is not a recommended course of action.
But included here for completeness.
Use the following to identify is tabbed
tabbed = (e.keyCode === 9 && e.type === 'keydown')?true:false;
I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?
document.addEventListener('keydown', function(event){
if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});
I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)
Just ensure none of the other three modifiers are pressed:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
The code below should solve your problem(Updated Code):
document.addEventListener("keydown", function (event) {
var map = [];
onkeyup = function(e){
map.push(e.key);
console.log(map);
if(map.length == 2){
console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
}
onkeydown = function(e){
// console.log(map);
}
}
});
If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!
You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.
Something like this should work:
var keysPressed = [];
function onPressOrRelease(event) {
if (event.type === "keydown") {
if (!keysPressed.includes(event.keyCode))
keysPressed.push(event.keyCode)
} else if (event.type === "keyup")
keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);
let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
if (ctrlQPressed)
console.log("pressed");
}
document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);
You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)
I have the following code which checks for "enter" key as well as prevent the use of > and < sign in the textbox.
<script type="text/javascript" language="javascript">
function checkKeycode(e) {
var keycode;
if (window.event) // IE
keycode = e.keyCode;
else if (e.which) // Netscape/Firefox/Opera
keycode = e.which;
if (keycode == 13) {
//Get the button the user wants to have clicked
var btn = document.getElementById(btnSearch);
if (btn != null) { //If we find the button click it
btn.click();
event.keyCode = 0
}
//Removed when above code was added 12-09-13
//CallSearch();
}
}
function CallSearch() {
var objsearchText = window.document.getElementById('txtSearchText');
var searchText;
if ((objsearchText!=null))
{
searchText = objsearchText.value;
searchText = searchText.replace(/>/gi, " >");
searchText = searchText.replace(/</gi, "< ");
objsearchText.value = searchText;
}
//This cookie is used for the backbutton to work in search on postback
//This cookie must be cleared to prevent old search results from displayed
document.cookie='postbackcookie=';
document.location.href="search_results.aspx?searchtext=";
}
</script>
How can I shorten the code to be more effecient and use the onBlur function and to use RegExp instead of replace? Or is replace a faster method than RegExp?
You are saying that you want to prevent < and > chars. Here is an easier way, just ignore these chars when the keydown event occurs on them.
Also I suggest to use jQuery - if you can.
http://api.jquery.com/event.which/
var ignoredChars = [188, 190]; // <, >
$('#myTextField').keydown(function(e) {
if(ignoredChars.indexOf(e.which) > -1) {
e.preventDefault();
e.stopPropagation();
return false;
}
})
.keyup(function(e) {
if(e.which === 13) {
$('#searchButton').click();
}
});
Just add this event handler to your textbox and remove the regexp replacements.
If you don't want characters to be input by user, surpress them as early as possible. This way you won't get in trouble fiddling them out of a big string later.
I have a huge entry form and fields for the users to input.
In the form user use tab key to move to next feild,there are some hidden fields and readonly textboxes in between on which tab key is disabled using javascript.
Now users finds difficult to use tab key and wants same functionality on down arrow key of the keyboard.
I was using the below code to invoke the tab key code on js but not working,please some body help me on this.
function handleKeyDownEvent(eventRef)
{
var charCode = (window.event) ? eventRef.keyCode : eventRef.which;
//alert(charCode);
// Arrow keys (37:left, 38:up, 39:right, 40:down)...
if ( (charCode == 40) )
{
if ( window.event )
window.event.keyCode = 9;
else
event.which = 9;
return false;
}
return true;
}
<input type="text" onkeydown=" return handleKeyDownEvent(event);" >
Using jQuery, you can do this :
$('input, select').keydown(function(e) {
if (e.keyCode==40) {
$(this).next('input, select').focus();
}
});
When you press the down arrow key (keyCode 40), the next input receives the focus.
DEMO
EDIT :
In Vanilla JS, this could be done like this :
function doThing(inputs) {
for (var i=0; i<inputs.length; i++) {
inputs[i].onkeydown = function(e) {
if (e.keyCode==40) {
var node = this.nextSibling;
while (node) {
console.log(node.tagName);
if (node.tagName=='INPUT' || node.tagName=='SELECT') {
node.focus();
break;
}
node = node.nextSibling;
}
}
};
};
}
doThing(document.getElementsByTagName('input'));
doThing(document.getElementsByTagName('select'));
Note that you'd probably want to map the up key too, and go to first input at last one, etc. I let you handle the details depending on your exact requirements.
This is my final working code:
$('input[type="text"],textarea').keydown( function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 40) {
e.preventDefault();
var inputs = $(this).parents('form').find(':input[type="text"]:enabled:visible:not("disabled"),textarea');
inputs.eq( inputs.index(this)+ 1 ).focus();
inputs.eq( inputs.index(this)+ 1 ).click();
}
});
If I understand correctly, some fields are read-only, so the tab key still activates them, even though they are read-only, and this is annoying, as you have to press the tab key perhaps several times to get to the next editable field. If that is correct, then an alternate solution would be to use the tabindex attribute on your input fields, indexing each one so that the read-only and otherwise non-editable fields aren't selected. You can find more info on the tabindex attribute here.
I just started adding JS-validation to a signup form and I want the username input field in a Twitter-style (using jQuery). That means that the input is limited to certain characters and other characters do not even appear.
So far, I've got this:
jQuery(document).ready(function() {
jQuery('input#user_login').keyup(function() {
jQuery(this).val( jQuery(this).val().replace(/[^a-z0-9\_]+/i, '') );
});
});
This solution works, but the problem is that the illegal character appears as long as the user hasn't released the key (please excuse my terrible English!) and the keyup event isn't triggered. The character flickers in the input field for a second and then disappears.
The ideal solution would be the way Twitter does it: The character doesn't even show up once.
How can I do that? I guess I'll have to intercept the input in some way.
If you want to limit the characters the user may type rather than the particular keys that will be handled, you have to use keypress, as that's the only event that reports character information rather than key codes. Here is a solution that limits characters to just A-Z letters in all mainstream browsers (without using jQuery):
<input type="text" id="alpha">
<script type="text/javascript">
function alphaFilterKeypress(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
return /[a-z]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("alpha");
input.onkeypress = alphaFilterKeypress;
};
</script>
Try using keydown instead of keyup
jQuery('input#user_login').keydown(function() {
Aside: You selector is slower than it needs to be. ID is unique, and fastest, so
jQuery('#user_login').keydown(function() {
Should suffice
You might want to consider capturing the keycode iself, before assigning it to the val
if (event.keyCode == ...)
Also, are you considering the alt, ctls, and shift keys?
if (event.shiftKey) {
if (event.ctrlKey) {
if (event.altKey) {
Thanks #TimDown that solved the issue! I modified your code a little so it accepts backspace and arrows for editing (I post a reply to use code formatting).
Thank you very much.
function alphaFilterKeypress(evt) {
evt = evt || window.event;
// START CHANGE: Allow backspace and arrows
if(/^(8|37|39)$/i.test(evt.keyCode)) { return; }
// END CHANGE
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
// I also changed the regex a little to accept alphanumeric characters + '_'
return /[a-z0-9_]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("user_login");
input.onkeypress = alphaFilterKeypress;
};
You can use the maxlength property in inputs and passwords: info (that's actually the way Twitter does it).