Skip to content

Instantly share code, notes, and snippets.

@brianjlandau
Created March 17, 2010 17:18
Show Gist options
  • Select an option

  • Save brianjlandau/335479 to your computer and use it in GitHub Desktop.

Select an option

Save brianjlandau/335479 to your computer and use it in GitHub Desktop.
// Example Usage:
// $('form.some-class').fieldsTabIndexFocus([
// 'input#record_name', 'textarea#record_description', 'select#some-input',
// 'fieldset#some-id li'
// ], 'input#record_name:first');
(function($) {
$.tabIndexManagers = [];
$.tabIndexManager = function(form, fields){
this.fields = fields;
this.form = form;
this.updateTabIndex();
$.tabIndexManagers.push(this);
};
$.updateAllTabIndexes = function(){
$.each($.tabIndexManagers, function(index, manager){
manager.updateTabIndex();
});
};
$.tabIndexManager.prototype = {
updateTabIndex: function(){
var self = this, tabindex = 1;
$.each(this.fields, function(index, selector){
$(selector, self.form).each(function(){
var $elm = $(this);
if ($elm.is(':input, a')){
this.tabIndex = tabindex;
tabindex++;
} else {
$elm.find(':input').each(function(){
this.tabIndex = tabindex;
tabindex++;
});
}
});
});
}
};
$.fn.fieldsTabIndexFocus = function(fields, focus){
if (this.length > 0){
var tab_manager = new $.tabIndexManager(this.slice(0,1), fields);
$(focus, this.slice(0,1)).focus();
return tab_manager;
} else {
return null;
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment