[英]How to advance to the next form input when the current input has a value?
我有一個包含很多條目的表格。 在當前文本框中輸入值后,我想將焦點更改為下一個文本框。 並且想繼續這個過程直到最后一個字段。 我的問題是,一旦我在文本框中輸入值,是否可以通過 Javascript 編碼模擬按 Tab 鍵時發生的情況。
在不按鍵盤上的 Tab 鍵的情況下,我想通過 Javascript 帶來相同的功能。 這可能嗎?
您只需要將焦點放在下一個輸入字段上(通過在該輸入元素上調用 focus() 方法),例如,如果您使用的是 jQuery,則此代碼將在按下 Enter 時模擬 Tab 鍵:
var inputs = $(':input').keypress(function(e){
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
不久前需要模擬選項卡功能,現在我已將其作為使用jquery的庫發布。
EmulateTab :一個 jQuery 插件,用於模擬頁面上元素之間的制表符。
您可以在演示中看到它是如何工作的。
if (myTextHasBeenFilledWithText) {
// Tab to the next input after #my-text-input
$("#my-text-input").emulateTab();
}
function nextField(current){
for (i = 0; i < current.form.elements.length; i++){
if (current.form.elements[i].tabIndex - current.tabIndex == 1){
current.form.elements[i].focus();
if (current.form.elements[i].type == "text"){
current.form.elements[i].select();
}
}
}
}
當與當前字段一起提供時,會將焦點跳轉到具有下一個選項卡索引的字段。 用法如下
<input type="text" onEvent="nextField(this);" />
我找不到可以做我想做的事情的答案。 我遇到了一些我不希望用戶按 Tab 鍵訪問的鏈接元素的問題。 這就是我想出的:
(請注意,在我自己的代碼中,我在allElements
行上使用a:not(.dropdown-item)
而不是a
,以防止用戶切換到a.dropdown-item
。)
function(event){
//Note that this doesn't honour tab-indexes
event.preventDefault();
//Isolate the node that we're after
const currentNode = event.target;
//find all tab-able elements
const allElements = document.querySelectorAll('input, button, a, area, object, select, textarea, [contenteditable]');
//Find the current tab index.
const currentIndex = [...allElements].findIndex(el => currentNode.isEqualNode(el))
//focus the following element
const targetIndex = (currentIndex + 1) % allElements.length;
allElements[targetIndex].focus();
}
這通過表單模擬選項卡,並在按下 Enter 鍵時將焦點放在下一個輸入上。
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var inputs = document.getElementsByClassName('input');
for (var i = 0; i < inputs.length; i++) {
if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
inputs[i+1].focus();
break;
}
}
在第一個問題中,您不需要在每個浪費的輸入上都使用事件偵聽器。
相反,監聽回車鍵並使用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();
}
}
};
一個事件偵聽器比許多更好,尤其是在低功耗/移動瀏覽器上。
這應該有效。 使用和不使用 tabindex。
var currentlyFocused = undefined; var tabableElements = undefined; /** * Compare function for element sort * @param {string | null} a * @param {string | null} b * @param {boolean} asc */ function sortCompare(a, b, asc = true) { let result = null; if (a == null) result = 1; else if (b == null) result = -1; else if (parseInt(a) > parseInt(b)) result = 1; else if (parseInt(a) < parseInt(b)) result = -1; else result = 0; return result * (asc ? 1 : -1); } /** * When an element is focused assign it to the currentlyFocused variable * @param {Element} element */ function registerOnElementFocus(element) { element.addEventListener("focus", function(el) { currentlyFocused = el.srcElement; }); } /** * Tab Trigger */ function onTabClick() { //Select currently focused element let currentIndex; tabableElements.forEach((el, idx) => { //return if no element is focused if (!currentlyFocused) return; if (currentlyFocused.isEqualNode(el)) { //assign current index and return currentIndex = idx; return; } }); //if theres no focused element or the current focused element is last start over let lastIndex = tabableElements.length - 1; let nextElementidx = currentIndex === undefined || currentIndex == lastIndex ? 0 : currentIndex + 1; //Focus currentlyFocused = tabableElements[nextElementidx]; currentlyFocused.focus(); } /** * Init must be run after all elements are loadead in the dom */ function init() { //Get all tab-able elements let nodeList = document.querySelectorAll("input, button, a, area, object, select, textarea, [tabindex]"); //To array for easier manipulation tabableElements = Array.prototype.slice.call(nodeList, 0); //Correcting tabindexes to ensure correct order tabableElements.forEach((el, idx, list) => { let tabindex = el.getAttribute("tabindex"); //-1 tabindex will not receive focus if (tabindex == -1) list.splice(idx, 1); //null or 0 tabindex in normal source order else if (tabindex == null || tabindex == 0) { list[idx].setAttribute("tabindex", 9999 + idx); } }); //sort elements by their tabindex in ascending order tabableElements.sort((elementA, elementB) => sortCompare(elementA.getAttribute("tabindex"), elementB.getAttribute("tabindex"))); //register focus event to elements tabableElements.forEach(el => registerOnElementFocus(el)); }
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Virtual tab</title> </head> <body onload="init()"> <div class="container"> <h3>Virtual Tab Demo</h3> <form> <div class="btn btn-primary" style="position: fixed;" onclick="onTabClick()"> Tab! </div> <br> <br> <button id="button1" type="button" onclick="alert('button 1')">Button1</button> <button id="button2" type="button" onclick="alert('button 2')">Button2</button> <br> <br> <input id="text" type='text'>text <br> <input id="password" type='password' tabindex="-1">password <br> <input id="number" type='number' tabindex="5">number <br> <input id="checkbox" type='checkbox'>checkbox <br> <input id="radio" type='radio'>radio <br> <br> <button id="button3" type="button" onclick="alert('button 3')">Button3</button> <button id="button4" type="button" onclick="alert('button 4')">Button4</button> <br> <br> <select id="select"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <br> <br> textarea <br> <textarea id="textarea"></textarea> <br> <br> <span id="span" tabindex="1">Focus other elements.</span> </form> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
如果你有 jQuery UI 這個小功能允許基本的標簽
function 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
}
}
在香草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)
}
}
我已經適配了ltiong_sh的答案來為我工作:
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.