Shuo/client/js/lib/jquery.tabComplete.js

68 lines
1.3 KiB
JavaScript
Raw Normal View History

2014-04-07 21:19:20 +00:00
/*!
* jquery-tab-complete
* https://github.com/erming/jquery-tab-complete
*
* Copyright (c) 2014 Mattias Erming <mattias@mattiaserming.com>
* Licensed under the MIT License.
*
2014-04-08 17:40:54 +00:00
* Version 0.2.0
2014-04-07 21:19:20 +00:00
*/
(function($) {
2014-04-08 17:40:54 +00:00
$.fn.tabComplete = function(list, options) {
var settings = $.extend({
appendSpace: false,
caseSensitive: false,
}, options);
2014-04-07 21:19:20 +00:00
var self = this;
if (self.size() > 1) {
return self.each(function() {
2014-04-08 17:40:54 +00:00
$(this).tabComplete(list, options);
2014-04-07 21:19:20 +00:00
});
}
2014-04-08 17:40:54 +00:00
// Keep the list stored in the DOM via jQuery.data() variable.
self.data('list', list);
2014-04-07 21:19:20 +00:00
var match = [];
self.on('keydown', function(e) {
var key = e.which;
if (key != 9) {
match = [];
return;
}
2014-04-08 17:40:54 +00:00
var text = self.val().trim().split(' ');
2014-04-07 21:19:20 +00:00
var last = text.splice(-1)[0];
if (!match.length) {
2014-04-08 17:40:54 +00:00
match = $.grep(self.data('list'), function(w) {
var l = last;
if (l == '') {
return;
}
if (!settings.caseSensitive) {
l = l.toLowerCase();
w = w.toLowerCase();
}
return w.indexOf(l) !== -1;
2014-04-07 21:19:20 +00:00
});
}
var i = match.indexOf(last) + 1;
if (i == match.length) {
i = 0;
}
if (match.length) {
last = match[i];
}
text.push(last);
2014-04-08 17:40:54 +00:00
self.val(text.join(' ') + (settings.appendSpace ? ' ' : ''));
2014-04-07 21:19:20 +00:00
return false;
});
};
})(jQuery);