Skip to content

Instantly share code, notes, and snippets.

@roooodcastro
Created March 22, 2017 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roooodcastro/0f596666bb85222940519726dadda068 to your computer and use it in GitHub Desktop.
Save roooodcastro/0f596666bb85222940519726dadda068 to your computer and use it in GitHub Desktop.
Selectize plugin - Select or preserve onBlur
/**
* Plugin: "preserve_on_blur" (selectize.js)
* Copyright (c) 2016 Eric M. Klingensmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Eric M. Klingensmith <eric.m.klingensmith@gmail.com>
*
* Based on methods used in restore_on_backspace plugin by Brian Reavis & contributors.
*/
Selectize.define('preserve_on_blur', function(options) {
var self = this;
options.text = options.text || function(option) {
return option[this.settings.labelField];
};
this.onBlur = (function(e) {
var original = self.onBlur;
return function(e) {
// Capture the current input value
var $input = this.$control_input;
var inputValue = $input.val();
// Do the default actions
original.apply(this, e);
// Set the value back
var searchResults = this.currentResults.items;
// If there's only one search result, auto select it
if (searchResults.length == 1) {
if (!self.items[0] || self.items[0] != searchResults[0].id) {
this.addItem(searchResults[0].id, true);
}
} else {
// If there's zero or multiple results, just keep the typed text
this.setTextboxValue(inputValue);
}
};
})();
} );
@raumi75
Copy link

raumi75 commented Nov 2, 2019

Hi, thanks for this plugin.Gists don't support pull requests. You might want to look at my fork. I added a trigger to the onChange() event so it behaves more like the regular select event.
Line 44 here:
https://gist.github.com/raumi75/06689de23d42d224651f7fcddf47eee2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment