I suspect what you really want is to move to the next field in the form.
If so, you can easily find the next form field and use .focus()
to focus it. For instance:
var fields = $(this).closest("form").find("input, textarea");
var index = fields.index(this) + 1;
fields.eq(
fields.length <= index
? 0
: index
).focus();
Example:
$(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
var fields = $(this).closest("form").find("input, textarea");
var index = fields.index(this) + 1;
fields.eq(
fields.length <= index
? 0
: index
).focus();
}
});
<form>
<div>
<label>
Field 1:
<input type="text">
</label>
</div>
<div>
<label>
Field 2:
<input type="text">
</label>
</div>
<div>
<label>
Field 3:
<input type="text">
</label>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you're using tabindex
to put fields in a different order than document order, you'll have to do a bit more work, basically sorting the result of find
on tabindex
and working from there. But that should get you going the right way.