Execute function when particular key is pressed if textbox has focus - javascript

I want to focus on a textbox which is located down in a webpage when a user presses the down key.
I know that I can do it by using the following code:-
if ( e.keyCode === 40 ) { // 40 is down key
// I m stuck here
}
Now, I am stuck in what to code in the body region. How to bring focus to the textbox whose id is "abc" for example. Any help will be appreciated. Thanks in advance
UPDATE
I tried this :-http://jsfiddle.net/9qAqM/ (helped by #iBlue)
$(document).ready(function(){
$("#xyz").keypress(function(e){
if ( e.which === 40 ) {
$('#abc').focus();
}
}) ;
});
Still, its not working

try this piece of code
$('#abc').focus();
or
document.getElementById('abc').focus();
UPDATE::
As per your code, since you are trying to detect the down arrow keys they are not detected by keypress event.They are detected by keydown event.So if you modify your code as per the below code it would work
$(document).ready(function(){
$("#xyz").keydown(function(e){
if ( e.which == 40 ) {
$('#abc').focus();
}
}) ;
});
Here is the working jsfiddle for your code

Check out the updated fiddle at http://jsfiddle.net/9qAqM/2/.
$('#xyz').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
$('#abc').focus();
}
});

If you are using jQuery try this:
if ($("#IdOfYourTextBox").is(':focus')) {
alert("TextBox is focused!");
}

Related

How to click a hyperlink using .click() in Jquery?

I am trying to read an article but I a am bored of pressing the hyperlink "next page" and tried to run the code below.
(what is the code for : Pressing enter will find the hyperlink of class "x-hidden-focus") and click it.
The code written below worked by clicking a button when pressing enterKey for another webpage, yet it didn't work with a hyperlink .I tried to run the code that is commented but neither codes fixed my problem.
The class of the hyperlink I want to press is ".x-hidden-focus"
This is the link to the article.
$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
//$(".x-hidden-focus")[0].click();
$(".x-hidden-focus").click();
}
});
NOTE: I am using this code as a userscript in tampermonkey (Hope this helps).
You could try to simply navigate to to the href described by the link you are trying to click:
document.location = $("a.x-hidden-focus").attr("href")
Which with your code would become :
$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
document.location = $("a.x-hidden-focus").attr("href");
}
});
Based on the article you have provided we can see that the html for the button you are trying to click is the following:
Next
However if you do press next we can see that there is now 2 buttons :
Previous
Next</p>
And now your code would be :
$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
document.location = $("a.x-hidden-focus:contains('Next')").attr("href");
}
});
EDIT
My assumptions that the class was already present on the element was wrong.
Since the class is only added after you hover the link you would need to find the link only based on the text:
$("a:contains('Next')");
You could however be more precise by using the container class:
$("div.step-by-step").find("a:contains('Next')").attr("href")
The button on the documentation page is dynamically created and the class doesn't exist on it unless you click/hover it. You will need to select the button by
$('a:contains("Next")')
then get the first one of the resulting three links and take its href
$('a:contains("Next")').eq(0).attr('href')
Now you can set the location
document.location = $('a:contains("Next")').eq(0).attr('href')
$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
document.location = $('a:contains("Next")').eq(0).attr('href')
}
});
Just need to add listener for click event like this:
$(document).on('keypress', function(e) {
if (e.keyCode === 13) {
$('.x-link').click();
}
$('.x-link').on('click', function() {
let url = $(this).attr('href')
window.open(url)
})
})
Here is example
As #bambam said You have to select the Link first by:
`$('a:contains("Next")')`
Then navigate to the href described by the link by:
$('a:contains("Next")').eq(0).attr('href')
And you can do the same for the Previous link.Your Final code would be:
$(document).keydown(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
document.location = $('a:contains("Next")').eq(0).attr('href')
}
else if(which == '16'){
document.location = $('a:contains("Previous")').eq(0).attr('href')
}
});
When you press Enter Keycode:13 you go to the next page.
When you press Shift Keycode: 16 you go to the previous page.

Simulate press in a link using keystroke

Hello I have this link for example
<a href"http://google.es">Link</a>
Is there any way using Javascript or similar that when I press for example the number 5 in the keyboard It´s the same as if I press the link with the mouse?
Thanks
you can use jQuery
$( document ).keypress(function( event ) {
event.charCode == 53 ? window.open("google.es","_self") : console.log('another key');
});
You can bind keypress event and sniff out the event.which and when the appropriate key is pressed you can programmatically click the a or link element.
Check this CodePen for the example.
Note: This example is using jQuery plugin.
Try this. Using jQuery.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function checkKey(e) {
var code;
if (e.keyCode) code = e.keyCode;
if (code == 53) { // replace the 53 with the keycode of your choice.
$('#myLink').trigger("click");
}
}
</script>
</head>
<body onkeydown="checkKey(event);">
<button id="myLink" onclick="window.location.href= 'https://google.com'">Link</button>
</body>
</html>
Keycode reference: http://www.foreui.com/articles/Key_Code_Table.htm
you can use the key press event in jquery
$(function() {
$(document).keypress(function(e) {
if (e.which === 53){
location.href = "http://google.es";
}
});
});
this is for the key 5 if you want to change key give asci value for that key

Detect Tab Key event on textbox on focus

I have a autocomplete textbox in a form and I want to detect whether user has focussed on the textbox from navigating through tab key press.I mean tabindex has been set up on different form fields and user can navigate fields by pressing tabs.Now I want to perform some action when user directly mouse click/foxus on the textbox and some other action when user has focussed on the textbox through tab.
Below is the code I was trying.But no matter everytime code is 0.
$('#tbprofession').on('focus', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('Tabbed');
}
else
{
alert('Not tabbed');
}
});
This code does not work.
Note:Before marking duplicate it will be good if you understand the question correctly.Else I can make it more clear with more elaborated description.
Anyone can show me some light?
You can try something like that :
$(document).on("keyup", function(e) {
if ($('#tbprofession').is(":focus")) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
} else {
alert('not tabbed');
}
}
});
fiddle : https://jsfiddle.net/xc847mrp/
You can use keyup event instead:
$('#tbprofession').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
console.log('I was tabbed!', code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input autofocus>
<input id='tbprofession'>
You could have an array of key events triggered anytime a user presses a key while on your page. Although this makes you think of a keylogger.
Or just keep the last key.
Or a boolean saying if the last key pressed was a TAB or not.
And on focus you can look at that variable.

Overwriting key events

How to overwrite or remove key events, that is on a website? I'm writing a script for GreaseMonkey and I want to make event on Enter button, but when I press the ENTER button, it triggers function on website.
EDIT 1: Here is the website, that I need to do this http://lockerz.com/auth/express_signup
One of these two should do it for you. I used the first one, although someone on SO told me the second one will work also. I went for the hammer.
Sorry, first one wasn't a cut and paste answer. I use using it to return up/down arrow control on a website. I changed it so that it identifies keycode 13 instead.
(function() {
function keykiller(event) {
if (event.keyCode == 13 )
{
event.cancelBubble = true;
event.stopPropagation();
return false;
}
}
window.addEventListener('keypress', keykiller, true);
window.addEventListener('keydown', keykiller, true);
})();
Searching quickly on SO:
jQuery Event Keypress: Which key was pressed?
Code from there:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
Without a library, use: http://jsfiddle.net/4FBJV/1/.
document.addEventListener('keypress', function(e) {
if(e.keyCode === 13) {
alert('Enter pressed');
return false;
}
});

How can I disabling backspace key press on all browsers?

I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.
Here's the code:
$(document).keypress(function(e){
var activeNodeName=document.activeElement.nodeName;
var activeElType=document.activeElement.type;
if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
return false;
} else {
if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
return false;
}
}
});
Any advice on what I'm doing wrong here?
Thanks!
I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.
Instead of keypress, try the keydown function, it will fire before the actual browser based hook. Also, putting in a preventDefault() function will assist in this. IE :
$(document).keydown(function(e){
e.preventDefault();
alert(e.keyCode);
});
Hope this helps.
The most Simple thing you can do is add the following one line in the very first script of you page at very first line
window.history.forward(1);
Most examples seem to be for the JQuery framework - Here an example for ExtJS
(I've been getting a lot of downvotes for this recently as the question now has JQuery tag on it, which it didn't previously. I can remove the answer if you like as isn't for JQuery but it's proven to help others not using that framework).
To use this add this code block to your code base, I recommend adding it inside the applications init function().
/**
* This disables the backspace key in all browsers by listening for it on the keydown press and completely
* preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
*/
Ext.EventManager.on(window, 'keydown', function(e, t) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.getKey() == e.BACKSPACE) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Use e.which instead of e.keyCode; jQuery normalizes this value across browsers.
http://api.jquery.com/keydown/
To determine which key was pressed,
examine the event object that is
passed to the handler function. While
browsers use differing properties to
store this information, jQuery
normalizes the .which property so you
can reliably use it to retrieve the
key code.
Then, use e.preventDefault(); to prevent the default behaviour of moving to the previous page.
<html>
<head>
<script type="text/javascript">
function stopKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 8) && (node.type!="text")) {return false;}
}
document.onkeypress = stopKey;
</script>
</head>
<body onkeydown="return stopKey()">
<form>
<input type="TEXTAREA" name="var1" >
<input type="TEXT" name="var2" >
</form>
</body>
</html
I had to add the onDownKey attribute to the body in order to get editing keys to go to the functions.
$(document).keydown(function(e) {
var elid = $(document.activeElement).is('input');
if (e.keyCode === 8 && !elid) {
return false;
}
});
Hope this might help you
Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...
Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.
I disable the "backspace" default on anything that is not a text area or text field - like this:
$(document).keydown(function(e){
console.log(e.keyCode+"\n");
var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
console.log(typeName+"\n");
// Prevent Backspace as navigation backbutton
if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
e.preventDefault();
}
//
})
Not sure where else one would want the normal behavior of a back-button other than in these two areas.
document.onkeydown = KeyPress;
function KeyPress(e) {
if (!e.metaKey){
e.preventDefault();
}
}

Categories