I am having a form with lots of entries. I would like to change my focus to the next textbox, once I entered the value in the current textbox. and want to continue this proc
Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses jquery.
EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.
You can see how it works in the demo.
if (myTextHasBeenFilledWithText) {
// Tab to the next input after #my-text-input
$("#my-text-input").emulateTab();
}
In the first question, you don't need an event listener on every input that would be wasteful.
Instead, listen for the enter key and to find the currently focused element use document.activeElement
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
if (nextInput) {
nextInput.focus();
}
}
};
One event listener is better than many, especially on low power / mobile browsers.
If you have jQuery UI this little function allows basic tabbing
handlePseudoTab(direction) {
if (!document.hasFocus() || !document.activeElement) {
return;
}
const focusList = $(":focusable", $yourHTMLElement);
const i = focusList.index(document.activeElement);
if (i < 0) {
focusList[0].focus(); // nothing is focussed so go to list item 0
} else if (direction === 'next' && i + 1 < focusList.length) {
focusList[i + 1].focus(); // advance one
} else if (direction === 'prev' && i - 1 > -1) {
focusList[i - 1].focus(); // go back one
}
}
I've adapter the answer of ltiong_sh to work for me:
function nextField(current){
var elements = document.getElementById("my-form").elements;
var exit = false;
for(i = 0; i < elements.length; i++){
if (exit) {
elements[i].focus();
if (elements[i].type == 'text'){
elements[i].select();
}
break;
}
if (elements[i].isEqualNode(current)) {
exit = true;
}
}
}
you just need to give focus to the next input field (by invoking focus()method on that input element), for example if you're using jQuery this code will simulate the tab key when enter is pressed:
var inputs = $(':input').keypress(function(e){
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
In vanilla JS:
function keydownFunc(event) {
var x = event.keyCode;
if (x == 13) {
try{
var nextInput = event.target.parentElement.nextElementSibling.childNodes[0];
nextInput.focus();
}catch (error){
console.log(error)
}
}