Skip to content

Instantly share code, notes, and snippets.

@HichemTab-tech
Last active July 29, 2023 19:25
Show Gist options
  • Save HichemTab-tech/8467bd5f558055c588dcad296fdbafa9 to your computer and use it in GitHub Desktop.
Save HichemTab-tech/8467bd5f558055c588dcad296fdbafa9 to your computer and use it in GitHub Desktop.
jQuery actionsRelay Plugin - Form Enter Key Navigation : This is a custom jQuery plugin called actionsRelay that enhances the behavior of HTML forms. With this plugin, users can efficiently navigate through form input fields by simply pressing the Enter key. The plugin allows for customization options, such as skipping hidden input fields and sp…
/**
* jQuery actionsRelay Plugin
* Form Enter Key Navigation
*
* Enhance the behavior of HTML forms by enabling Enter key navigation through input fields.
*
* Usage:
* $(selector).actionsRelay({
* okBtn: 'auto', // Set to 'auto' to submit the form upon reaching the last input, or provide a custom button selector.
* ignoreClasses: '', // Add classes to be ignored when navigating through inputs (comma-separated, e.g., 'ignore1,ignore2').
* });
*
* @param {Object} [options] - Customization options (optional).
* @param {string} [options.okBtn='auto'] - Define the action when reaching the last input. Set to 'auto' to submit the form, or provide a custom button selector.
* @param {string} [options.ignoreClasses=''] - Specify classes to be ignored during navigation (comma-separated).
*/
$.fn.actionsRelay = function (options = {}) {
let settings = $.extend({
okBtn: 'auto',
ignoreClasses: '',
}, options);
let form = $(this);
let inputs = form.find('input, textarea');
form.submit(function(e){
e.preventDefault();
});
inputs.on('keyup', function (e) {
if (e.keyCode === 13) {
let index = inputs.index(this);
while (
index > -1 &&
index < inputs.length &&
(
$(inputs[index + 1]).hasClass(settings.ignoreClasses) ||
!$(inputs[index + 1]).is(':visible')
)
) {
index++;
}
if (index > -1 && index + 1 < inputs.length) {
inputs.eq(index + 1).focus();
}
else if(index + 1 >= inputs.length) {
if (settings.okBtn === 'auto') {
form.find('button[type="submit"]').click();
}
else{
$(settings.okBtn).click();
}
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment