如果文本框有焦点,按下特定键时执行功能

Execute function when particular key is pressed if textbox has focus

本文关键字:功能 执行 文本 焦点 如果      更新时间:2023-09-26

我想关注用户按下向下键时位于网页下方的文本框。我知道我可以通过使用以下代码来做到这一点:-

if ( e.keyCode === 40 ) { // 40 is down key
    // I m stuck here
}

现在,我被困在身体区域的代码中。例如,如何将焦点放在id为"abc"的文本框上。任何帮助都将不胜感激。提前感谢

更新我试过这个:-http://jsfiddle.net/9qAqM/(由@iBlue帮助)

$(document).ready(function(){
$("#xyz").keypress(function(e){
            if ( e.which === 40 ) { 
$('#abc').focus();
}         
}) ;
});

尽管如此,仍不起作用

尝试这段代码

$('#abc').focus();

document.getElementById('abc').focus();

更新::根据您的代码,由于您正在尝试检测向下箭头键,keypress事件没有检测到它们。它们由keydown事件检测到。因此,如果你按照下面的代码修改你的代码,它将工作

 $(document).ready(function(){
    $("#xyz").keydown(function(e){
                if ( e.which == 40 ) { 
                        $('#abc').focus();
                }         
             }) ;
});

这是您的代码

的工作jsfiddle

查看更新后的fiddlehttp://jsfiddle.net/9qAqM/2/.

$('#xyz').keypress(function(event){
     var keycode = (event.keyCode ? event.keyCode : event.which);
     if(keycode == '13'){
           $('#abc').focus();   
     }
 });

如果您正在使用jQuery,请尝试以下操作:

if ($("#IdOfYourTextBox").is(':focus')) {
alert("TextBox is focused!");
}