如何将光标移动到下一个文本字段?

问题描述:

在我的工作过程中,我尝试通过按Enter键将焦点从一个文本字段移至另一个文本字段。我已经找到了可能的答案在下面的链接:如何将光标移动到下一个文本字段?

How to go to next textbox when enter is pressed?
Move Cursor to next text Field pressing Enter

但都未为我工作。我的代码:

<script> 
$('input[type='text']').keyup(function(e) { 
    if(e.keyCode == 13) { 
     $(this).next().focus(); 
    } 
}); 
</script> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
<input type='text' /> 
+0

关于您的实际问题在 - 它与服务器端无关。您所做的完全是客户端,并通过将脚本标记移动到输入下方进行修复。 –

+1

你为什么要用enter?从字面上看,没有人会期望这种行为。 – Slime

+1

@Waxi你是对的。使用Enter来进入下一个输入将是无用的,因为没有人会使用它。切换输入焦点的默认键是** Tab键**,其工作不需要javascript – Aloso

只需更新$('input[type='text']')$('input[type="text"]')。你有没有封闭的字符串。

Working codepen here

+0

其实我正在PHP中写入变量$ var内的代码。然后echo $ var。这就是为什么我使用$('input [type ='text']')。否则它会显示错误, **解析错误:语法错误,第4行的/opt/lampp/htdocs/1.php中出现意外的'文本'(T_STRING)** –

+0

@DragonBall但是在删除了php部分之后,解决方案Nicolae应该工作吗? –

+0

@ Al.G。也是这个不工作,http://codepen.io/anon/pen/aJMpEj –

$(document).ready(function() { 
 

 
\t $('form').on('submit', function (event) { 
 
\t  event.preventDefault(); 
 
\t }) 
 

 
\t $('input[type="text"]').keyup(function(event) { 
 
\t  if(event.keyCode === 13) { 
 
     \t $(this).next().focus(); 
 
\t  } 
 
\t }); 
 

 
})
<script src="https://code.jquery.com/jquery-3.2.1.slim.js"></script> 
 
<form> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
    \t <input type="text"/> 
 
</form>

+0

因为jQuery不包括在内。代码本身看起来很好。 – Aloso

+0

固定!感谢指出这一点 - 有人可以给我一个手,如何将jquery包含在片段中?这里是一个小提琴现在:https://jsfiddle.net/qbbcmrnk/ –

这里发生的事情:

<!-- Start loading the page --> 
<script> 
// execute javascript. Note that there 
// are no inputs on the page currently - they will be loaded later 

// This selector matches nothing: 
$("input[type='text']").keyup(function(e) { 
    if(e.keyCode == 13) { 
     $(this).next().focus(); 
    } 
}); 
</script> 
<!-- JavaScript executed. Now add inputs to the page --> 
<input type='text' /> 
<input type='text' /> 

你能做什么或者是移动输入下面的<script>(最简单的)或移动keyup监听到的onload功能:

$(function(){ 
// i.e. wrap your js here 

// the js here will be executed only after page has loaded 
}); 
+0

向下移动脚本将无法正常工作。 http://codepen.io/anon/pen/PpLpbp –

+0

@DragonBall抱歉,我忘记修复报价。现在应该工作。 –

+0

@ AI.G。我现在添加一个图像。这不起作用,https://postimg.org/image/ozvdutibz/ –