-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.select-filter.min.js
1 lines (1 loc) · 2.31 KB
/
jquery.select-filter.min.js
1
!function($){$.fn.selectFilter=function(options){var defaults={caseSensitive:false,clearInputOnEscape:true,disableRegex:true,filterClass:"filter-bar",inputLocation:"below",inputPlaceholder:"type to filter list",minimumCharacters:3,minimumSelectElementSize:3,searchDelay:200,searchFromBeginning:false,width:-1};options=$.extend(defaults,options);var self=this;if(!self||self.get(0).tagName!=="SELECT"){return false}var clone=self.children().clone();var width=options.width;if(width===-1){width=self.width()}var widthStr=width.toString();if(isFinite(widthStr)){widthStr+="px"}self.css("width",widthStr);var name="";if(typeof self.attr("name")==="undefined"){name="undefined_name"}else{name=self.attr("name").replace(/\]/g,"").replace(/\[/g,"")}if(typeof self.attr("size")==="undefined"||self.attr("size")<options.minimumSelectElementSize){self.attr("size",options.minimumSelectElementSize)}var filterElement=$("<input>",{id:"input_"+name,type:"text",placeholder:options.inputPlaceholder,"class":options.filterClass,style:"display: block; width: "+widthStr});self.addClass(name+"_select").css({display:"block"});if(options.inputLocation==="above"){self.before(filterElement)}else{self.after(filterElement)}if(options.clearInputOnEscape){$("#input_"+name).on("keydown",function(key){if(key.which===27){$(this).val("")}})}var keyDelayTimeout;var filteringStarted=false;var oldSearchText=null;$("#input_"+name).on("keyup",function(){clearTimeout(keyDelayTimeout);var searchText=$(this).val();if(!filteringStarted&&searchText.length<options.minimumCharacters){return}filteringStarted=true;keyDelayTimeout=setTimeout(function(){if(oldSearchText!==null){if(searchText.length<=oldSearchText.length){self.children().remove();self.append(clone)}}oldSearchText=searchText;if(!options.caseSensitive){searchText=searchText.toLowerCase()}if(options.disableRegex){searchText=searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}if(options.searchFromBeginning){searchText="^"+searchText}var pattern=new RegExp(searchText);self.children().each(function(i,selected){var option_value=$(this).text();if(!options.caseSensitive){option_value=option_value.toLowerCase()}if(!pattern.test(option_value)){$(selected).remove()}});if(self.children().length===0){self.append("<option disabled>(No results.)</option>")}clearTimeout(keyDelayTimeout)},options.searchDelay)});return this}}(jQuery);