Skip to content

Instantly share code, notes, and snippets.

@michaeljacobdavis
Created August 29, 2012 00:10
Show Gist options
  • Save michaeljacobdavis/3505527 to your computer and use it in GitHub Desktop.
Save michaeljacobdavis/3505527 to your computer and use it in GitHub Desktop.
Autotab
$.fn.autotab = function () {
var inputEvents = "input";
if (!("oninput" in document || "oninput" in $("<input>")[0])) {
inputEvents += " keypress";
}
return this.each(function () {
var $this = $(this);
$this.on(inputEvents, "input[maxlength]", function (e) {
var $this = $(this);
if ($this.attr("maxlength") <= $(this).val().length) {
$this.focusNextField();
}
});
return this;
});
};
$.fn.focusNextField = function () {
return this.each(function () {
var $this = $(this);
var elements = $(this).parents('div.line').find('input');
var index = elements.index(this);
if (index > -1 && (index + 1) < elements.length) {
elements.eq(index + 1).focus().on("keydown", function (e) {
if (!$(this).val().length) {
if (e.which == 8) {
$this.focus();
$this.val(function () {
return $this.val();
});
}
}
});
}
return this;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment