Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Last active June 9, 2022 19:01
Show Gist options
  • Save carloscarucce/fbdb64c16735b61f07b03424e1ab4676 to your computer and use it in GitHub Desktop.
Save carloscarucce/fbdb64c16735b61f07b03424e1ab4676 to your computer and use it in GitHub Desktop.
Auto tab between N fields.
(function(){
/**
* Focus on the next input
*
* @param current
* @param to
*
* @see https://bartamediagroup.com/auto-tab-html-input-fields/
*/
function tab(current,to){
if (current.getAttribute && current.value.length == current.getAttribute("maxlength") && to.focus) {
to.focus();
}
}
/**
* Auto tab between all the input fields passed as parameters.
* All them MUST have maxlength property filled.
*
* Example:
*
* const input1 = document.getElementById('input1');
* const input2 = document.getElementById('input2');
* const input3 = document.getElementById('input3');
* autotab(input1, input2, input3);
*
* @param inputs
*/
window.autotab = function(inputs) {
const l = arguments.length;
for (let i = 0; i < l; i++) {
if (i+1 < l) {
const input = arguments[i];
const dest = arguments[i + 1];
input.addEventListener('input', function(){
tab(input, dest);
});
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment