使用向上/向下箭头导航HTML表单

时间:2014-10-03 15:52:27

标签: javascript html forms

我有一个带有表示键值对的输入元素的表单 当用户希望这样做时,这些输入元素在页面内动态生成
表格看起来有点像这样:
form example

这是一行的一些示例代码,由两个输入元素组成:

<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>


如何使用按钮导航表单,不使用任何外部库

例:使用按钮从蓝色输入到绿色输入,使用按钮从绿色输入到蓝色输入。

伪代码基本上都是我需要的

感谢。

1 个答案:

答案 0 :(得分: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>