Make enter key behave like tab key in Javascript - javascript

So far i have this being called on keypress.
function chkenter()
{
e = event.keyCode;
if (e == 13)
{
event.keyCode = 9;
return false;
}
}
but even though i set the keycode to 9 it doesn't tab over to the next control. How can i accomplish this? I'm working in Asp Classic.
What I ultimately want is for the focus to move to the next element. The next element's id, however, is not determined completely because its id was set in a loop, but at this point it exists. How can i set focus to the next control is the question.

It is an IE only script, so if you try to run it on firefox it wont work.
For it to work on IE, remove "return false;" from your code and dont forget to atach this function into "onkeydown" event.

You can do this using jQuery like so:
function checkKey(e){
if( e.keyCode == 13 ){ // if enter key
var e = jQuery.Event('keydown'); // create a manual event
e.which = e.charCode = 0;
e.keyCode = 9; // set the new event to "tab"
$(this.target).trigger(e); // trigger the new event (on the document)
return false; // cancels the original "enter" event from executing
}
}
// lets say you bind the event on the whole document...
$(document).on('keydown', checkKey);

Related

Trying to make a keyup used for 2 functions based on a timer

There is a button linked to a machine that sends a keypress to this app
Sometimes the button will "double tap" the key combination (Double shift + S)
Tried some of the responses over here: "How to trap double key press in javascript?"
as it seems along the lines of what I need but can't seem to get any to work
function myFunction(xml) {
// Start on keypress
document.addEventListener('keyup', function(e) {
if (e.keyCode == 83 && e.shiftKey)
// Set a baseline for first keypress to compare later
var lastKeypressTime = 0;
// Code to run after initial keypress here
// Basically a bunch of TTS reading from XML until either it finishes, or a button is pressed for a reload
// I think this is kind of along the lines of what I'm after but can't quite implement it properly
// Detect the keypress
document.addEventListener('keyup', function(e) {
if (e.keyCode == 83 && e.shiftKey)
// Set time of keypress to compare
var thisKeypressTime = new Date();
// if time between first keypress is greater than 2 seconds, let the page reload
if (thisKeypressTime - lastKeypressTime >= 2000)
window.location.reload();
else
// Otherwise, ignore all keypresses until the 2 seconds (at least) has passed before the button press works again
})
})
}
Due to the button being... imperfect.. When it registers a single press as a double press, the page is reloaded instantly
Basically needing either the first keypress that "starts" the TTS to never register a faulty double press, or have any consecutive keypress ignored entirely until after a certain period has passed or something to that extent
Any guidance or alternatives to what I'm trying to accomplish would be greatly appreciated :)
const delta = 1500;
let lastPress = 0;
function handleKeyPress(event) {
let currentPress = new Date();
if (event.key === "S" && event.shiftKey) {
if (currentPress - lastPress <= delta) {
alert("Shift + s");
currentPress = 0;
}
lastPress = currentPress;
}
}
document.addEventListener("keyup", handleKeyPress);
This is a snippet that works, you have to define the lastPress variable outside your function, and I don't understand why you're trying to register two listeners for the keyup event. Once that you've defined your listener handler, it will be called every time the event that you're listening on is fired; this is why you have to save the lastPress and the currentPress times.
P.S.
Obviously instead of alert something on the double keypress you can run your own function.

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.

JavaScript keyboard events and detection

I am trying to stay clear of jQuery and want to detect if the left or right key is pressed. I am having trouble just getting this to work.
var keyPress = function(event) {
var keyCode = event.keyCode;
if (keyCode == 37)
//do something
if (keyCode == 39)
//do something
}
document.onkeydown = keyPress(event);
The problem I am having is that I just cannot detect any keyboard events.
Any help would be greatly appreciated.
You need to pass the function reference to onkeydown
document.onkeydown = keyPress;
what you are doing to calling the function keyPress and passing the value returned by it as the onkeydown handler, in this case undefined.

Capture key press without placing an input element on the page?

How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input elements (input boxes, textareas, etc)
For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.
Attaching a keydown event to document works in all the major browsers:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z");
}
};
For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.
jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:
$(document).keypress(function(e){
var checkWebkitandIE=(e.which==26 ? 1 : 0);
var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);
if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});
Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064
Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:
$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
$("body").append("<p>ctrl+z detected!</p>");
});
For modern JS, use event.key!
document.addEventListener("keypress", function onPress(event) {
if (event.key === "z" && event.ctrlKey) {
// Do something awesome
}
});
NOTE: The old properties (.keyCode and .which) are Deprecated.
Mozilla Docs
Supported Browsers
Detect key press, including key combinations:
window.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode == 90) {
// Ctrl + z pressed
}
});
Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.
Code & detects ctrl+z
document.onkeyup = function(e) {
if(e.ctrlKey && e.keyCode == 90) {
// ctrl+z pressed
}
}
Attach a listener to the keydown event instead of keypress, since the latter is now deprecated.
window.addEventListener('keydown', keyDownHandler);
The keydown event triggers continuously while the key is pressed. If you wanna have it fire only once, inside the handler use the event.repeat property as so:
keyDownHandler(event) {
if (!event.repeat) {
<code here will only be executed once while the key is pressed>
}
}
Remember to remove the listener when not needed anymore.
window.removeEventListener('keydown', keyDownHandler);

event is not defined in mozilla firefox for javascript function?

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

Categories

Resources