专注于下一个输入(jquery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10539113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
focusing on next input (jquery)
提问by domino
I've got four inputs that each take one number. What I want to do is set the focus automatically to the next input once the number has been set. They all have the class "inputs".
我有四个输入,每个输入一个数字。我想要做的是在设置数字后自动将焦点设置到下一个输入。他们都有“输入”类。
This didn't quite work:
这不太奏效:
$(".inputs").keydown(function () {
$(this).next().focus();
});
回答by Selvakumar Arumugam
I would suggest setting maxlength as 1 to each textbox and switch to next one once the val.length
and the maxlength
is same.
我建议设定最大长度为1到每个文本框,并切换到下一个曾经的val.length
和maxlength
是一样的。
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
Edit:Spent some time for the following (not fully tested, but basic tests worked fine)
编辑:花了一些时间进行以下(未完全测试,但基本测试工作正常)
1. Allowing just numeric chars
2. Allow some control like del, backspace, e.t.c
3. Backspace on empty textbox will move to prev textbox
4. charLimit var to dynamically decide how many char you want to restrict.
Code:
代码:
$(function() {
var charLimit = 1;
$(".inputs").keydown(function(e) {
var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];
if (e.which == 8 && this.value.length == 0) {
$(this).prev('.inputs').focus();
} else if ($.inArray(e.which, keys) >= 0) {
return true;
} else if (this.value.length >= charLimit) {
$(this).next('.inputs').focus();
return false;
} else if (e.shiftKey || e.which <= 48 || e.which >= 58) {
return false;
}
}).keyup (function () {
if (this.value.length >= charLimit) {
$(this).next('.inputs').focus();
return false;
}
});
});
回答by Jivings
That will just get the next element, whatever it is. You probably want:
那只会得到下一个元素,不管它是什么。你可能想要:
$(".inputs").keyup(function () {
$(this).next(".inputs").focus();
});
Also, key up not keydown or it will change too soon.
另外,key up 不是 keydown 否则它会改变得太快。
回答by sathish gowda
try this
尝试这个
jQuery.extend(jQuery.expr[':'], {
focusable: function (el, index, selector) {
return $(el).is('a, button, :input,[tabindex]');
}
});
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
// Get all focusable elements on the page
var $canfocus = $(':focusable');
var index = $canfocus.index(document.activeElement) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
回答by Samuel Vicent
Here is the code I use for making enter key to behave as tab, i.e, focus to next element when pressing the Enter key or focusing previous element when pressing shift+Enter.
以下是我使用的代码,用于将Enter键表达为选项卡,即在按ENTER键按ENTER键时对焦于下一个元素,或按SHIFT + ENTER时聚焦上一个元素。
1) Essentially:
1) 本质上:
tabables = $("*[tabindex != '-1']:visible");
var index = tabables.index(element);
tabables.eq(index + 1).focus();
2) Here you are a "class" that encapsulates the behaviour, having in mind fordward and backwards and valid focusable elements.
2)这里是一个封装行为的“类”,记住向前和向后以及有效的可聚焦元素。
I hope it helps and if some code suits your needs, feel free to adapt to your needs :)
我希望它有所帮助,如果某些代码适合您的需求,请随时适应您的需求:)
EnterAsTab = function () {
this.ENTER_KEY = 13;
};
EnterAsTab.prototype.init = function () {
this.listenOnEnterKey();
};
EnterAsTab.prototype.listenOnEnterKey = function () {
var me = this;
$('form input').on('keypress', function (event) {
if (event.which === me.ENTER_KEY) {
if (!event.shiftKey)
me.findNextFocusableElement(this);
else
me.findPreviousFocusableElement(this);
event.preventDefault();
}
}
);
};
EnterAsTab.prototype.findNextFocusableElement = function (element) {
this.findFocusableElement(element, this.increaseIndex);
};
EnterAsTab.prototype.findPreviousFocusableElement = function (element) {
this.findFocusableElement(element, this.decreaseIndex);
};
EnterAsTab.prototype.findFocusableElement = function (element, callable) {
var tabables = $("*[tabindex != '-1']:visible");
var index = tabables.index(element);
var counter = 1;
var nextElement = undefined;
try {
while (true) {
if ((nextElement = tabables.eq(index + counter)).length === 0) {
break;
}
if (this.isFocusableElement(nextElement)) {
var newIndex = callable.call(this, index, counter);
tabables.eq(newIndex).focus();
break;
} else {
counter++;
}
}
} catch (error) {
console.log(error);
}
};
EnterAsTab.prototype.increaseIndex = function (index, counter) {
return (index + counter);
};
EnterAsTab.prototype.decreaseIndex = function (index, counter) {
return index - counter;
};
EnterAsTab.prototype.isFocusableElement = function (element) {
return ['SELECT', 'TEXTAREA'].indexOf(element.prop('tagName')) > -1 ||
element.is(':text') ||
element.is(':checkbox') ||
element.is(':radio');
};
var enterAsTab = new EnterAsTab();
enterAsTab.init();
回答by Phil Cook
If you just want to look at the next input but you have say separators in the way like this
如果您只想查看下一个输入,但您已经像这样说分隔符
<input type="number" pattern="[0-9]*" inputmode="numeric" maxlength="2" placeholder="DD" name="dobday" id="dobday">
<div class="separator">/</div>
<input type="number" pattern="[0-9]*" inputmode="numeric" maxlength="2" placeholder="MM" name="dobmonth" id="dobmonth">
<div class="separator">/</div>
<input type="number" pattern="[0-9]*" inputmode="numeric" maxlength="4" placeholder="YYYY" name="dobyear" id="dobyear">
You will need to you the this code to get all the next items and settle on the first input found:
您需要使用此代码来获取所有下一个项目并确定找到的第一个输入:
$('input#dobday,input#dobmonth,input#dobyear').on('input', function(e) {
if (jQuery(this).val().length >= parseInt(jQuery(this).attr("maxlength"), 10)) {
if (jQuery(this).attr('id') === 'dobyear') {
jQuery(this).blur();
} else {
jQuery(this).nextAll('input:first').focus();
}
}
}
回答by ggzone
After searching and developing I end up in a crossbrowser snippet which makes it possible to focus the next input field with same class depending on maxlength (tested with 1 character) also with the ability to focus back via backspace button:
在搜索和开发之后,我最终得到了一个跨浏览器片段,这使得可以根据 maxlength(用 1 个字符测试)将下一个输入字段与相同的类集中在一起,还可以通过退格按钮向后集中:
Javascript (jquery):
Javascript(jQuery):
var codeCharInput = 'input.code-char';
$(codeCharInput+':first').focus();
$(codeCharInput).keyup(function(e) {
if ((e.which == 8 || e.which == 46)) {
$(this).prev(codeCharInput).focus().val($(this).prev().val());
} else {
if (this.value.length == this.maxLength) {
$(this).next(codeCharInput).focus();
}
}
});
HTML:
HTML:
<input type="text" name="chars[]" maxlength="1" class="code-char" />
<input type="text" name="chars[]" maxlength="1" class="code-char" />
<input type="text" name="chars[]" maxlength="1" class="code-char" />
<input type="text" name="chars[]" maxlength="1" class="code-char" />
回答by Mikeys4u
This will keep focus on the text box, after using next without naming the class or id.
这将继续关注文本框,在使用 next 后不命名类或 id。
$(this).hide();
$(this).next().show();
$('input[type=text]').focus();
回答by Melbourne2991
Building on @Vega's answer
以@Vega 的回答为基础
inputs.keydown(function(e) {
var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];
$(this).val('');
if (e.which == 8 && this.value.length == 0) {
$(this).prev(inputs).focus();
} else if ($.inArray(e.which, keys) >= 0) {
return true;
} else if (this.value.length > charLimit) {
$(this).next(inputs).focus();
return false;
} else if (e.shiftKey || e.which <= 48 || e.which >= 58) {
return false;
}
}).keyup (function () {
if (this.value.length >= charLimit && $(this).next(inputs).attr('type') === 'text') {
$(this).next(inputs).focus();
return false;
}
});
If a user clicks on an input that already has a value it will override it, instead of going to the next input, it will also only focus on text inputs. I had a situation where I had a submit input next to the text inputs and if using backspace could accidentally redirect the page.
如果用户点击一个已经有值的输入,它会覆盖它,而不是去下一个输入,它也只会关注文本输入。我遇到过在文本输入旁边有一个提交输入的情况,如果使用退格键可能会意外重定向页面。
回答by sandeep kumar
This is the code that complete your all needs.
这是完成您所有需求的代码。
$(".input").keyup(function(e) {
if (e.which == 8 || e.which == 46){
//backspace / Delete
$(this).val('');
$(this).prevAll('input:first').focus();
}
else
{
var spcl_arr = ["~","!","@", "#", "$", "%", "^", "&", "*", "(", ")", "+","-", "=", "." ,"/"];
if(e.which == 13){ // Enter Kay
return false;
}
else if(jQuery.inArray($(this).val(), spcl_arr) !== -1 ){
$(this).val('');
$(this).focus();
return false;
}else{
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
if (this.value.length == this.maxLength) {
$(this).next('.input').focus();
}
}else{
$(this).val('');
$(this).focus();
return false;
}
}
}
});
});
回答by Anurag Uniyal
Use keyup
e.g.
使用keyup
例如
$(".inputs").keyup(function () {
$(this).next().focus();
});?
See it in action http://jsfiddle.net/qygB2/