July 11, 2013
Select 2: display currently selected value
Example is based on following SHA:24716bc872.
Select2 is a great alternative for the standard select box (check it out: Select2).
One project required a specific behavior to be added to Select2. When the user clicks on the searchbox, the currently selected value disappears and if you want it back, you need to type it back in.
Since I was going to add several Select2 on the same page containing up to 6000 options each, I needed a way to have the current value available for edit or copy/paste. When clicking on the select box, current value must be displayed as follow:
I added a new global boolean value (called keepValOnSearch
) that indicates whether or not the current selected option must be displayed or not:
if (initial === true && opts.keepValOnSearch && search.val() == "" && opts.element.attr("multiple") == undefined) {
var selected = opts.element.find(":selected");
search.val(selected.text());
}
The selected value can only be applied to the single select boxes.