Friday 25 September 2015

Prevent Form Submission When User Presses the Enter key / Move to next textbox when user presses enter key


 When we filling out the web forms, if we hit the Enter key accidentally, then the form will submit, it makes us frustrating every time.

To prevent this you can use the code below. Instead of submitting, it actually focus / moves to next input boxes when we press Enter key.

$('body').on('keydown', 'input, select, textarea', function(e) {
    var self = $(this)
            , form = self.parents('form:eq(0)')
            , focusable
            , next
            ;
    if (e.keyCode == 13) {
        focusable = form.find('input,a,select,textarea').filter(':visible');
        next = focusable.eq(focusable.index(this) + 1);
        //  console.log(next.attr('type'));
        if (next.length && (next.attr('type') != 'button')) {
            next.focus();
        } else {
            form.submit();
        }
        return false;
    }
});