Skip to content

Commit e89a851

Browse files
committed
Merge pull request select2#715 from vitalets/default-initselection-hidden
Default initSelection() for hidden element
2 parents fa90897 + 88a86e5 commit e89a851

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

select2.js

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,11 +380,11 @@ the specific language governing permissions and limitations under the Apache Lic
380380
}
381381
group.children=[];
382382
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
383-
if (group.children.length || query.matcher(t, text(group))) {
383+
if (group.children.length || query.matcher(t, text(group), datum)) {
384384
collection.push(group);
385385
}
386386
} else {
387-
if (query.matcher(t, text(datum))) {
387+
if (query.matcher(t, text(datum), datum)) {
388388
collection.push(datum);
389389
}
390390
}
@@ -1663,6 +1663,20 @@ the specific language governing permissions and limitations under the Apache Lic
16631663
if ($.isFunction(callback))
16641664
callback({id: selected.attr("value"), text: selected.text(), element:selected});
16651665
};
1666+
} else if ("data" in opts) {
1667+
// install default initSelection when applied to hidden input and data is local
1668+
opts.initSelection = opts.initSelection || function (element, callback) {
1669+
var id = element.val();
1670+
//search in data by id
1671+
opts.query({
1672+
matcher: function(term, text, el){
1673+
return equal(id, opts.id(el));
1674+
},
1675+
callback: !$.isFunction(callback) ? $.noop : function(filtered) {
1676+
callback(filtered.results.length ? filtered.results[0] : null);
1677+
}
1678+
});
1679+
};
16661680
}
16671681

16681682
return opts;
@@ -1850,6 +1864,22 @@ the specific language governing permissions and limitations under the Apache Lic
18501864
if ($.isFunction(callback))
18511865
callback(data);
18521866
};
1867+
} else if ("data" in opts) {
1868+
// install default initSelection when applied to hidden input and data is local
1869+
opts.initSelection = opts.initSelection || function (element, callback) {
1870+
var ids = splitVal(element.val(), opts.separator);
1871+
//search in data by array of ids
1872+
opts.query({
1873+
matcher: function(term, text, el){
1874+
return $.grep(ids, function(id) {
1875+
return equal(id, opts.id(el));
1876+
}).length;
1877+
},
1878+
callback: !$.isFunction(callback) ? $.noop : function(filtered) {
1879+
callback(filtered.results);
1880+
}
1881+
});
1882+
};
18531883
}
18541884

18551885
return opts;

0 commit comments

Comments
 (0)