如何强制“输入密钥”充当“制表键”用javascript? [英] How to force "enter key" to act as "tab key" using javascript?

查看:72
本文介绍了如何强制“输入密钥”充当“制表键”用javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个充满要填充的表格的网站上工作,我需要按下退出按钮时焦点移动到下一个输入控件,就像按标签一样。
我发现当keypressed是13时移动焦点的代码,但这需要将元素的ID集中在

I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do. I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on

<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />

<script type="text/javascript">

    function noNumbers(e) {

        keynum = e.which;

        if (keynum == 13)
            document.getElementById("Text2").focus();

    }
</script>

我需要一个通用函数,当按键代码是13即输入触发默认事件按9即标签,当然是在Javascript

I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript

推荐答案

这将处理多个输入字段。

This will handle multiple input fields.

以下是jQuery版本:
http:// jsfiddle .net / TnEB5 / 3 /

Here is the jQuery version: http://jsfiddle.net/TnEB5/3/

$('input').keypress(function(e) {
    if (e.which == 13) {
        $(this).next('input').focus();
        e.preventDefault();
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text"  />
<input id="Text2" type="text" />
<input id="Text3" type="text" />

这是纯粹的javascript版本:
http://jsfiddle.net/TnEB5/5/
(您可能希望以不同的方式获得兄弟姐妹)

Here is the pure javascript version: http://jsfiddle.net/TnEB5/5/ (you probably want to get the sibling differently)

function tab(e) {
    if (e.which == 13) {
        e.target.nextSibling.nextSibling.focus();
        e.preventDefault();
    }
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
    var input = inputs[x];
    input.onkeypress = tab;
}

<input id="Text1" type="text"  />
<input id="Text2" type="text" />
<input id="Text3" type="text" />

这篇关于如何强制“输入密钥”充当“制表键”用javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆