javascript – 使用jquery在输入上选择下一个字段

我有一个html表单,每当按下Enter键时,都会选择下一个字段.
这是一个代码.

 $(document).on("keydown","input",function(event) {
    	if (event.which === 13) {
    		event.stopPropagation();
    		event.preventDefault();
    		$(this).nextAll("input").eq(0).focus();
    	}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    	<table>
    		<tr>
    			<td>Medical Record No.</td><td><input type="text" name="labNo" /></td>
    		</tr>
    		<tr>
    			<td>Age/sex </td><td><input type="text" name="age" />
    				<select id="age">
    					<option value="Year">Year</option>
    					<option value="Month">Month</option>
    				</select>
    				<select id="sex">
    					<option value="Male">Male</option>
    					<option value="Female">Female</option>
    				</select>
    			</td>
    		</tr>
    		<tr>
    			<td>Phone </td>
    			<td><input type="text" name="" value="-,-" /></td>
    		</tr>
    		<tr>
    			<td colspan="2"><input type="button" id="patBtn" value="Save (S)" accesskey="s" />
    				<input type="reset" value="Set Default (D)" accesskey="d" />
    			</td>
    		</tr>
    	</table>	
    </form>

这不起作用.

最佳答案
无论html结构如何,这都应该有效

$(document).on("keydown","input",function(event) {
if (event.which === 13 || event.keyCode === 13) {
    event.stopPropagation();
    event.preventDefault();
    var position = $(this).index('input');
    $("input").eq(position+1).focus();
}
 });

也适用于选择:

$(document).on("keydown, keyup","input, select",function(event) {
if (event.which === 13 || event.keyCode == 13) {
    event.stopPropagation();
    event.preventDefault();
    var position = $(this).index('input, select');
    $("input, select").eq(position+1).focus();
}
 });

jsfiddle:http://jsfiddle.net/xh0m7pzu/1/

转载注明原文:javascript – 使用jquery在输入上选择下一个字段 - 代码日志