I am currently trying to focus the next input type when the user presses on enter by using Jquery. However, it doesn't detect the keypress for some reason.
The input types are inside a css class named mGrid.
function addFocusSupport() {
$(".mGrid").find('input').each(function (index, element) {
// Here we get all the TextFields
alert($(this));
$(this).on("keypress",
function (e) {
if (e.KeyCode() === 13) {
// Focus next textfield
alert("Enter Pressed");
var nextElement = $('[index="' + (this.Index + 1) + '"]');
nextElement.focus();
alert(nextElement);
e.preventDefault();
}
// TODO: For last TextField, do nothing
});
});
}
So what I am trying to do: The user fills in the first input, press enter and automatically the next text box is selected. See it as a tab pressed.
But the event after if (e.KeyCode() === 13) {
is never triggered?
I am currently trying to focus the next input type when the user presses on enter by using Jquery. However, it doesn't detect the keypress for some reason.
The input types are inside a css class named mGrid.
function addFocusSupport() {
$(".mGrid").find('input').each(function (index, element) {
// Here we get all the TextFields
alert($(this));
$(this).on("keypress",
function (e) {
if (e.KeyCode() === 13) {
// Focus next textfield
alert("Enter Pressed");
var nextElement = $('[index="' + (this.Index + 1) + '"]');
nextElement.focus();
alert(nextElement);
e.preventDefault();
}
// TODO: For last TextField, do nothing
});
});
}
So what I am trying to do: The user fills in the first input, press enter and automatically the next text box is selected. See it as a tab pressed.
But the event after if (e.KeyCode() === 13) {
is never triggered?
-
it's
e.keyCode
with a minus k – sheplu Commented Oct 11, 2017 at 7:37 -
keyCode
is not a function.so usee.keyCode
– prasanth Commented Oct 11, 2017 at 7:44
3 Answers
Reset to default 8In my case, the following code is working fine.
$('body').on('keydown', 'input, select', function(e) {
if (e.which === 13) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
}
return false;
}
});
Change:
if (e.KeyCode() === 13) {
To:
if (e.which === 13) {
KeyCode()
is not the proper way to get the keycode. You are thinking of event.keyCode
, which is deprecated. If you are using jQuery, event.which
is normalized to work on all browsers. Without jQuery, make sure you check all cases:
var key = event.which || event.charCode || event.keyCode
To focus the next input element, do this:
$(this).next('input').focus();
you can use the following code
$(function() {
$(".mGrid >input").off('keyup').on('keyup', function(e) {
if (e.which === 13) {
$(this).next('input').focus();
}
});
});
here a working Jsfiddle demo
hope this will help you