Daenu Daenu - 7 months ago 46
Javascript Question

When preventing Enter key to submit AJAX form focus on next input isn't working

A small problem which I can't find a solution for (maybe I googled with wrong keywords):

The situation:

I prevent a form being submitted by hitting the Enter Key (13).
To be noted that the form will be submitted by AJAX, therefore there will be no page reload.

Preventing the Enter Key is a simple task and it works:

$(document).on('keypress', 'input', function (e) {
if (e.which === 13) {
return false;
}
});


The problem:

The focus on the next input is not working because of the
return false
.

If I omit the
return false
part, naturally the form is submitted by AJAX and the
focus()
is working.


$(document).on('keypress', 'input', function (e) {
if (e.which === 13) {
// Simplifying the selector of the next input
// because this isn't the problem
$(this).next().focus();
return false;
}
});


Any ideas on how to solve that?

Answer

Try by calling a function in your if condition and having $(this).next().focus(); in that function. In the callback function you can return false to prevent form submit.