2016-03-13 39 views
0

我有一个表单,我希望ENTER的动作移动到下一个输入字段而不是提交表单。我已经尝试了下面的代码和一百个变体,但我明显做错了什么。 enter image description here将ENTER函数更改为TAB

24行总是计算0的长度,所以27从不执行。 这是因为文字而不是图像:

$('form input').keydown(function(e) { 
    // The this keyword is <div id="input_form"> 
    if(e.keyCode == 13){ 

     e.preventDefault(); // cancel default 13 key behaviour (submitting form) 
     var n = $(this).next('input').length; 
     console.log("nexts=" + n); 
     if($(this).next('input').length) { // if there's another field 
      $(this).next('input').focus(); // move focus to next field in form 
     } 
     else { 
      $(this).blur(); 
     } 

    } 
}); 

形式是

<form action="" class="my_input_form" enctype="multipart/form-data" id="my_input_form_5" method="post" name=""> 

    <!--   First Name   --> 
    <div id="first_name_wrap" class="field_wrap" > 
     <label for="first_name" id="first_name_label" class="form_label">First Name</label> 
     <br /> 
     <input id="first_name" class="field_input" name="first_name" placeholder="" type="text" value="<?php echo $first_name?>"> 

     <div class="form_field_error" id="first_name_error" style="display:none;"></div> 
    </div> 

    <!--   Last Name   --> 
    <div id="last_name_wrap" class="field_wrap"> 
     <label for="last_name" id="last_name_label" class="form_label">Last Name</label> 
     <br /> 
     <input id="last_name" class="field_input" name="last_name" placeholder="" type="text" value="<?php echo $last_name?>"> 
     <div class="form_field_error" id="last_name_error" style="display:none;"></div> 
    </div> 

有谁看到这个问题?

+0

为什么第一个代码是图像?你能把它作为文本提供吗? –

+1

是的,请参阅上文。 – Steve

回答

1

.next()

获取的每个元件的紧接兄弟在该组的 匹配的元素。如果提供了选择器,则只有与选择器匹配时才会检索下一个 兄弟

您有第一个父div,这意味着.next("input")是空的,因为没有兄弟元素。你需要做的是这样的:

$(this).parent().next(".field_wrap").find("input").length 

这将:

  1. 进入的$(this)
  2. 转到下一个元素的父元素(即与class="field_wrap"下一个元素)
  3. 查找第一个输入元素
  4. 抓取长度
+0

谢谢。我知道了!如果在$(this).parent()。next(“。field_wrap”)。find(“input”)中的值为1,那么我将焦点移动到$(this).parent()。next(“ 。.field_wrap “)发现(” 输入“)聚焦();并将焦点转移到下一个输入。我有一种感觉,有一种更优雅的方式来做到这一点,但它确实做到了我想要的。 – Steve