I'm writing a small jQuery form routine designed to help a user fill in a group of bank sort code fields. There are 3 fields - when the user has filled in 2 numbers in one field, the cursor is automatically focus() on the next field.
However the problem arises if the user decides t开发者_如何学Co shift+tab back to the previous field. If this field already contains 2 characters, the cursor doesn't stay within that field but jumps forward again.
HTML:
<div class="formItem sortCode clearfix">
<input type="text" maxlength="2">
<input type="text" maxlength="2">
<input type="text" maxlength="2">
</div>
jQuery:
var $sortCollection = $('.sortCode input');
$('.sortCode input').keyup(function(event) {
var sortValue = $(this).val();
var sortPosition = $sortCollection.index(this);
if (!(event.keyCode == 9 && event.shiftKey)) {
if (sortValue.length == 2 && sortPosition != 2) {
sortPosition += 1;
$sortCollection.eq(sortPosition).focus().select();
}
}
});
I have a feeling the issue is to do with the keyup event being triggered when the shift key is released but I'm not sure. Please could someone take a look.
Try this:
if (!(event.keyCode == 16 || event.keyCode == 9)) {
if (sortValue.length == 2 && sortPosition !== 2) {
sortPosition += 1;
$sortCollection.eq(sortPosition).focus().select();
}
}
I think what you want is to ignore shift key click, just add
if (event.keyCode == 16) return;
after
$('.sortCode input').keyup(function(event) {
note: this will not affect event.shiftKey
$('.formItem input[type=text]').focus(function(){
if ($(this).length == 2 ) {
$(this).next('.formItem input[type=text]').focus();
}
});
Try to work this into your code, the keystrokes are not checked but the focus is controlled by the value of the input box. If the input box is brought into focus has a length of 2 then the next input box is brought into focus. This is should fall through until an input box that is not a length of two is found.
精彩评论