将光标移动到下一个文本字段按Enter键 [英] Move Cursor to next text Field pressing Enter
问题描述
我的表单中有多个文本字段,我希望用户在一个文本字段中输入数据,然后按回车键,光标移动到当前文本字段旁边的另一个文本字段。
I have multiple text fields in my form and I want when user enters data in one text field and press enter that the cursor moves to another text-field which is next to current text field. I visited some question but didn't find them useful.
$("#username").keypress(function (event) {
alert("inside function");
if(event.keyCode == 13) {
textboxes = $("input.username");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1];
nextBox.focus();
nextBox.select();
event.preventDefault();
return false;
}
}
});
这是我的代码,我试过
,最后一个文本字段,然后表单将提交的鼠标点击按钮不与输入新闻。
this is my code which i have tried an other thing that when the data entered in last text field then the form will submit on mouse click on the button not with enter press.
推荐答案
这应该工作: ()。
This should work:
$(".username").keyup(function (event) {
if (event.keyCode == 13) {
textboxes = $("input.username");
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1];
nextBox.focus();
nextBox.select();
}
event.preventDefault();
return false;
}
});
ENTER 不触发按键 code>在所有浏览器中使用,而使用
keyup
。还将eventlistener附加到每个 input
而不是一个包装器。
ENTER doesn't trigger keypress
in all browsers, used keyup
instead. Also attached eventlistener to each input
instead of a wrapper.
您的带有事件委托的代码也可以稍作更改:
Your code with event delegation will also work with a slight change:
currentBoxNumber = textboxes.index(event.target);
这个
上面的句子是指包装,而不是输入
, event.target
指引发事件的实际元素。
this
on above sentence would refer to the wrapper instead of the input
, event.target
refers to the actual element which fired the event.
这篇关于将光标移动到下一个文本字段按Enter键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!