From dacf51361dada44a03c9a3047aa18c43077bc4ac Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 27 Feb 2013 16:53:44 -0800 Subject: [PATCH] Default local initSelection returns the actual selected items Fix for issue #934. The default initSelection uses a matcher to find items that match the selection, but if the data is hierarchical what the matcher returns may actually be grouping elements, so they can't be treated as a list of matching items. This fix runs the matcher but rather than using its return value it collects the matching item(s) into a closure-scoped variable and then returns that. --- select2.js | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/select2.js b/select2.js index f5f9084f..db736308 100644 --- a/select2.js +++ b/select2.js @@ -1801,13 +1801,18 @@ the specific language governing permissions and limitations under the Apache Lic // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var id = element.val(); - //search in data by id + //search in data by id, storing the actual matching item + var match = null; opts.query({ matcher: function(term, text, el){ - return equal(id, opts.id(el)); + var is_match = equal(id, opts.id(el)); + if (is_match) { + match = el; + } + return is_match; }, - callback: !$.isFunction(callback) ? $.noop : function(filtered) { - callback(filtered.results.length ? filtered.results[0] : null); + callback: !$.isFunction(callback) ? $.noop : function() { + callback(match); } }); }; @@ -2034,15 +2039,20 @@ the specific language governing permissions and limitations under the Apache Lic // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var ids = splitVal(element.val(), opts.separator); - //search in data by array of ids + //search in data by array of ids, storing matching items in a list + var matches = []; opts.query({ matcher: function(term, text, el){ - return $.grep(ids, function(id) { + var is_match = $.grep(ids, function(id) { return equal(id, opts.id(el)); }).length; + if (is_match) { + matches.push(el); + } + return is_match; }, - callback: !$.isFunction(callback) ? $.noop : function(filtered) { - callback(filtered.results); + callback: !$.isFunction(callback) ? $.noop : function() { + callback(matches); } }); };