From 6df7ccf6c59c71694c3ff806cdfc0f834e34e9f0 Mon Sep 17 00:00:00 2001 From: WouterJ Date: Tue, 13 Jan 2015 02:26:24 +0100 Subject: [PATCH 1/4] Added basic autocompletion support --- Resources/public/js/jquery.autocomplete.js | 64 ++++++++++++++++++++++ Resources/views/Base/scripts.html.twig | 1 + 2 files changed, 65 insertions(+) create mode 100644 Resources/public/js/jquery.autocomplete.js diff --git a/Resources/public/js/jquery.autocomplete.js b/Resources/public/js/jquery.autocomplete.js new file mode 100644 index 0000000..391475a --- /dev/null +++ b/Resources/public/js/jquery.autocomplete.js @@ -0,0 +1,64 @@ +/** +* A small plugin to add autocompletion features for paths +* in browsers. +* +* @author Wouter J +*/ +jQuery.fn.cmfAutoComplete = function (options) { + options = jQuery.extend({ + // The element to put the data in, this has to be a element + // null: use the list attribute to find the datalist + // string: specify a custom selector + datalist_selector: null, + // A callback to retrieve the data, it should always return an array. + data: function (path) { return []; }, + }, options); + + var $input = $(this); + var $autocompleteList; + var cache = {}; + var previousBase; + + // find datalist + if (options.datalist_selector) { + $autocompleteList = $(options.datalist_selector); + } else if ($(this).attr('list')) { + $autocompleteList = $('#' + $(this).attr('list')); + } else { + throw 'No datalist selected'; + } + + if ('DATALIST' !== $autocompleteList.prop('tagName')) { + throw 'The configured datalist element should be a element, <' + $autocompleteList.prop('tagName').toLowerCase() + '> given.'; + } + + // find autocompletion values + $input.on('keyup', function (e) { + // arrows are used to navigate through the data list, don't update it then + if (e.keyCode >= 37 && e.keyCode <= 40) { + return; + } + + var path = $(this).val(); + var base = path.substr(0, path.lastIndexOf('/') + 1); // get everything except the child + + // skip if still in same node + if (base === previousBase) { + return; + } + previousBase = base; + + // cache node + if (!cache[base]) { + cache[base] = options.data(path); + } + + // clear datalist + $autocompleteList.empty(); + + // add new autocomplete values + cache[base].forEach(function (child) { + $autocompleteList.append('