Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $.fn.ac = function (options) {
- options = $.extend({}, $.fn.ac.defaults, options);
- var element = $(this);
- var index = -1;
- //Generate the lists that will be used for ac
- var ul = $('<ul />').css({ display: 'none'}).insertAfter(this);
- ul.attr('id', 'ac_' + $.data(this));
- //when the focus is lost of the input hide the ac list. 200ms so if we click the list it
- //will get caught.
- element.blur(function (e) {
- setTimeout(function () {
- ul.hide();
- }, 200)
- });
- //observe the field with keyup
- $(this).keyup(function (e) {
- var value = $(this).val().match('[^ ]*$')[0];
- switch (e.which) {
- case 8: //Backspace
- case 13: //Enter
- case 27: //Escape
- case 37: //Left
- case 38: //Up
- case 39: //Right
- case 40: //Down
- case 46: //Delete
- break;
- default:
- if (value.length >= 3) {
- //Ajax call. atm substituted with a static content.
- $.getJSON(options.url + '?' + options.param + '=' + value, function (data) {
- //clear the list
- ul.find('li').remove();
- //Render list and bind the up down array keys.
- $.each(data, function (key, item) {
- $('<li />').html(item).appendTo(ul);
- });
- //Show if we got one or more hits
- if (ul.find('li').length > 0) {
- ul.show();
- }
- //on a li click change the last word in the input box with the li one
- ul.find('li').click(function (e) {
- $.fn.ac.select(ul, element, $(this));
- index = -1;
- });
- });
- }
- break;
- }
- e.preventDefault();
- });
- $(this).keydown(function (e) {
- var testIndex = index;
- switch (e.which) {
- case 13: //Enter
- if (index == -1) {
- console.log('hej');
- $(this).parents('form:first').submit();
- return true;
- }
- $.fn.ac.select(ul, element, ul.find('li:eq(' + testIndex + ')'))
- index = -1;
- return false;
- break;
- case 46: //Delete
- case 8: //Backspace
- case 27: //Escape
- ul.hide();
- index = -1;
- break;
- case 38: //Up
- testIndex = index - 1;
- e.preventDefault();
- break;
- case 40: //Down
- testIndex = index + 1;
- e.preventDefault();
- break;
- }
- //Default is prevented so lets move the mother fucker..
- if (e.isDefaultPrevented()) {
- var elm = ul.find('li:eq(' + testIndex + ')');
- if (elm.length > 0) {
- ul.find('li:eq(' + index + ')').removeClass('ac-selected');
- index = testIndex;
- elm.addClass('ac-selected');
- }
- }
- });
- };
- $.fn.ac.select = function (ul, element, li) {
- element.val(element.val().replace(/[^ ]*$/, li.html()) + ' ');
- element.focus();
- ul.hide();
- }
- $.fn.ac.defaults = {
- url : 'ac.json',
- param : 'p_prefix'
- }
Add Comment
Please, Sign In to add comment