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 to 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With