Created
June 13, 2013 23:24
-
-
Save nathanaelnsmith/5778270 to your computer and use it in GitHub Desktop.
Auto Tab Form fields with maxlength set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var autoTab = { | |
keysPressed : 0, | |
init : function () { | |
this.keyEvents(); | |
}, | |
keyEvents : function () { | |
var self = this; self.keyEvents.validKey = false; | |
$('input[maxlength]').on('keypress', function(e){ | |
self.keyEvents.validKey = true; | |
if ($(this).attr('type') == 'number' && String.fromCharCode(e.which).match(/^\d+$/) == null) { | |
return false; | |
} | |
}); | |
$('input[maxlength]').on('keyup', function (e) { | |
var nextIndex = $('input,select,button').index($(this)) + 1; | |
self.form = $(this).parents('form'), self.keysPressed--; | |
/* Get right charcode if numberpad is used */ | |
if (self.keyEvents.validKey && (e.which >= 96 && e.which <= 105)) { | |
var newKey = String.fromCharCode(e.which - 48); | |
} else { | |
var newKey = String.fromCharCode(e.which); | |
} | |
/* Check if character max is hit */ | |
if (self.keyEvents.validKey && $(this).val().length < $(this).attr('maxlength')) { | |
self.keyEvents.tab = false; | |
} else if (self.keyEvents.validKey && ($(this).val().length > $(this).attr('maxlength'))) { | |
$(this).val($(this).val().replace(newKey,'')); | |
if(!self.keysPressed) { | |
self.tab(nextIndex); | |
} | |
} else if (self.keyEvents.validKey) { | |
self.tab(nextIndex); | |
} | |
}); | |
$('input[maxlength]').on('keydown', function (e) { | |
self.keyEvents.validKey = false; | |
self.keysPressed++; | |
}); | |
}, | |
tab : function (nextIndex) { | |
var self = this; | |
if (typeof $('input,select,button')[nextIndex] !== "undefined") { | |
$('input,select,button')[nextIndex].focus(); | |
} else { | |
self.form.find('button[type=submit], input[type=submit]').focus(); | |
} | |
self.keyEvents.validKey = false; | |
} | |
} | |
autoTab.init(); | |
})($); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment