The input
event will not fire if the element already has empty value because there's no value change.
A keyup
check for backspace press should suffice. Assuming the input elements are always direct siblings as in your example:
$('input').on('input propertychange', function() {
if (this.value.length >= this.maxLength) {
$(this).next().focus();
}
}).keyup(function(e) {
if (e.which === 8 && !this.value) {
$(this).prev().focus();
}
});
Fiddle
I've added a propertychange
listener as fallback for old IE, but you can remove it if you don't feel like using this ugly hack to support old IE. Also I've swapped .select()
by .focus()
so that it doesn't select the entire field upon focusing, but that is up to you too. =]
The e.which === 8
check is so that it only moves to the previous field by pressing the backspace key, but in case you'd like to move to the previous input even if the user erases the field value through other means (e.g. delete key or cut/delete context menu) you can remove the e.which === 8
too, though that wouldn't make much sense UX-wise imho.