Skip to content

Commit 1ab192a

Browse files
committed
option to hide the search field if there are just a few results. closes select2#4 and closes select2#6
1 parent 7cd54f5 commit 1ab192a

1 file changed

Lines changed: 22 additions & 8 deletions

File tree

select2.js

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,8 @@
255255
formatResult: function (data) { return data.text; },
256256
formatSelection: function (data) { return data.text; },
257257
formatNoMatches: function () { return "No matches found"; },
258-
formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; }
258+
formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
259+
minimumResultsForSearch: 0
259260
}, opts);
260261

261262
element = opts.element;
@@ -382,8 +383,7 @@
382383

383384
this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
384385

385-
this.updateResults();
386-
this.ensureHighlightVisible();
386+
this.updateResults(true);
387387
this.alignDropdown();
388388
this.dropdown.show();
389389
this.focusSearch();
@@ -511,7 +511,10 @@
511511
}
512512
};
513513

514-
AbstractSelect2.prototype.updateResults = function () {
514+
/**
515+
* @param initial whether or not this is the call to this method right after the dropdown has been opened
516+
*/
517+
AbstractSelect2.prototype.updateResults = function (initial) {
515518
var search = this.search, results = this.results, opts = this.opts;
516519

517520
search.addClass("select2-active");
@@ -551,7 +554,7 @@
551554
var d = data.results[i];
552555
$(this).data("select2-data", d);
553556
});
554-
this.postprocessResults();
557+
this.postprocessResults(data, initial);
555558
})});
556559
};
557560

@@ -737,15 +740,28 @@
737740
}
738741
};
739742

740-
SingleSelect2.prototype.postprocessResults = function () {
743+
SingleSelect2.prototype.postprocessResults = function (data, initial) {
741744
var selected = 0, self = this;
745+
746+
// find the selected element in the result list
747+
742748
this.results.find(".select2-result").each(function (i) {
743749
if ($(this).data("select2-data").id === self.opts.element.val()) {
744750
selected = i;
745751
return false;
746752
}
747753
});
754+
755+
// and highlight it
756+
748757
this.highlight(selected);
758+
759+
// hide the search box if this is the first we got the results and there are a few of them
760+
761+
if (initial===true) {
762+
this.search.toggle(data.results.length>=this.opts.minimumResultsForSearch);
763+
}
764+
749765
};
750766

751767
SingleSelect2.prototype.onSelect = function (data) {
@@ -898,8 +914,6 @@
898914
});
899915

900916
this.updateSelection(data);
901-
// preload all results
902-
this.updateResults();
903917
}
904918

905919
// set the placeholder if necessary

0 commit comments

Comments
 (0)