2014-10-03 57 views
1

我有一個表單,其中包含表示鍵值對的輸入元素。
這些輸入元素是在用戶需要時在頁面內動態生成的。

形式看起來有點像這樣:
form example

下面是一排一些示例代碼,由兩個輸入元素:使用向上/向下箭頭導航HTML表單

<tr id='1523459952424.153'> 
<td class='w50'> 
    <input type='text' name='kp_src[]' placeholder='Key'/> 
</td> 
<td class='w50'> 
    <input type='text' name='kp_dest[]' placeholder='Value'/> 
</td> 
<td> 
    <!-- 
    I excluded this part of the code for the sake of cleanliness, 
    this would be where the remove button lives its happy life. 
    --> 
</td> 
</tr> 


如何啓用導航與形式按鈕,不使用任何外部圖書館

例:從藍色輸入到與按鈕綠色投入,從綠色的輸入與按鈕,藍色的輸入。

僞代碼基本上是我所需要的。


謝謝。

+0

你會監視按鍵事件,如果該鍵碼的向下或向上箭頭一致,關注下輸入線。 – tymeJV 2014-10-03 15:53:47

+0

如果'input'元素不在同一個'tr'中,我該怎麼做? – 0x47686F7374 2014-10-03 15:59:30

+0

DOM遍歷 - 可能會更容易與jQuery(我知道它說沒有外部庫,但嘿) – tymeJV 2014-10-03 16:00:47

回答

0

tymeJV的評論讓我思考如何方便它實際上是在我的情況我會使用以下僞代碼輸入元素的keyup事件:

define a var named foo 
if key is down arrow 
    set foo to the next sibling of the current row 
else if key is up arrow 
    set foo to the previous sibling of the current row 
otherwise 
    abort 

define a var named bar 
if current input is the first input in the current row 
    set bar to the first input in foo 
else if current input is second input in the current row 
    set bar to the second input in foo 
otherwise 
    abort 

set focus to bar 


我可能已經發布了問題太早了,但我希望它對未來的其他人有用。

謝謝。


編輯:我還沒有時間去測試(甚至寫信,哈哈),直到今天。我會在下面發佈我的最終代碼,以防有人發現它有用。

的Javascript:

// obj - the source element 
// event - the event data 
// i  - child index of the textbox 
function form_vert_nav(obj, event, i) { 
    var o = ((event.keyCode == 38 || event.keyCode == 40) ? obj.parentNode.parentNode : null); 
    if (event.keyCode == 38) { // up 
     o = o.previousSibling; 
    } else if (event.keyCode == 40) { // down 
     o = o.nextSibling; 
    } else { 
     return; 
    } 
    if (o == null) { 
     // keyCode wasn't 38 or 40 and magically slipped through the else, 
     // or the sibling simply doesn't exist (more likely). 
     return; 
    } 
    if ((o = o.getElementsByTagName(obj.tagName)[i]) == null) { 
     // 404 Element Not Found 
     return; 
    } 
    o.focus(); 
} 


HTML:

<tbody> 
<tr> 
    <td><input type='text' onkeydown='form_vert_nav(this, event, 0);'/></td> 
    <td><input type='text' onkeydown='form_vert_nav(this, event, 1);'/></td> 
</tr> 
<tr> 
    <td><input type='text' onkeydown='form_vert_nav(this, event, 0);'/></td> 
    <td><input type='text' onkeydown='form_vert_nav(this, event, 1);'/></td> 
</tr> 
<tr> 
    <td><input type='text' onkeydown='form_vert_nav(this, event, 0);'/></td> 
    <td><input type='text' onkeydown='form_vert_nav(this, event, 1);'/></td> 
</tr> 
</tbody> 
相關問題