1. Add dynamic load CSS file does not need to introduce CSS CSS all generated dynamically in JS.
2. Do not need additional tags only need an input box and the default specifies a class class named "Inputelem" of course, you can also configure the parameters of the current parent container to add a default class name Parentcls (also can configure themselves), Because you need a hidden field after the input box matches the value, you need to hide the field to add a class "Hiddencls" Of course also supports its own configuration parameters.
/**
* JS Fuzzy query
* @author Tugenhua
* @date 2013-11-19
* @param 1. Current input Add Targetcls
* 2. Hidden fields inside the unified add the same name Hiddencls
* 3. Add a class name to each parent element parentcls
*/
function AutoComplete (options) {
This.config = {
Targetcls: '. Inputelem ',//input box target element
Parentcls: '. Parentcls ',//parent class
Hiddencls: '. Hiddencls ',//hidden domain input
Searchform: '. Jqtransformdone ',//form form
HOVERBG: ' HOVERBG ',//mouse move up the background
OUTBG: ' OUTBG ',//mouse Move Down background
Isselecthide:true,//Click the dropdown box to hide
URL: ',//URL interface
height:0,//defaults to 0 if not set then highly adaptive
Manyselect:false,///input box multiple select default False single
Renderhtmlcallback:null,//KeyUp the callback function after rendering the data
Callback:null,//Click on an item to provide a callback
Closedcallback:null//The callback function when clicking on an X button in the input box
};
This.cache = {
Currentindex:-1,
Oldindex:-1,
Inputarrs: []//Multiple selection time input box value into the array
};
This.init (options);
}
Autocomplete.prototype = {
Constructor:autocomplete,
Init:function (options) {
This.config = $.extend (this.config, Options | | {});
var self = this,
_config = Self.config,
_cache = Self.cache;
The mouse clicks the input box time
$ (_CONFIG.TARGETCLS). each (function (Index,item) {
/*
* Prohibit Ctrl + V and Sticky events
*/
$ (item). Unbind (' paste ');
$ (item). bind (' Paste ', function (e) {
E.preventdefault ();
var target = E.target,
Targetparent = $ (target). closest (_CONFIG.PARENTCLS);
$ (this). Val (');
$ (_config.hiddencls,targetparent) && $ (_config.hiddencls,targetparent). Val (');
});
$ (item). KeyUp (function (e) {
_cache.inputarrs = [];
var targetval = $.trim ($ (this). Val ()),
KeyCode = E.keycode,
Elemheight = $ (this). Outerheight (),
Elemwidth = $ (this). Outerwidth ();
If the value of the input box is empty, then the value of the hidden field is emptied.
if (Targetval = = "") {
var curparents = $ (this). closest (_CONFIG.PARENTCLS);
$ (_config.hiddencls,curparents). Val (');
}
var targetparent = $ (this). parent ();
$ (targetparent). css ({' position ': ' relative '});
if ($ ('. Auto-tips ', targetparent). length = = 0) {
Dynamically Create a Drop-down box container at initialization time
$ (targetparent). Append ($ (' <div class= "auto-tips hidden" ></div> "));
$ ('. Auto-tips ', targetparent). css ({' position ': ' absolute ', ' top ': elemheight, ' left ': ' 0px ', ' z-index ': 999, ' width ': Elemwidth, ' border ': ' 1px solid #ccc '});
}
var curindex = Self._keycode (keycode);
if (Curindex >-1) {
Self._keyupanddown (targetval,e,targetparent);
}else {
if (Targetval!= ') {
Self._dopostaction (targetval,targetparent);
}
}
});
Loss of focus If you do not click or move up and down directly input then the current input box value situation hidden field values
$ (item). blur (function (e) {
var target = E.target,
Targetparent = $ (target). closest (_CONFIG.PARENTCLS);
if ($ (this). attr ("Up") | | $ (this). attr (' down ')) {
Return
}else {
$ (this). Val (');
$ (_config.hiddencls,targetparent). Val (');
}
});
});
Block Form form default ENTER key submit
$ (_config.searchform). each (function (Index,item) {
$ (item). KeyDown (function (e) {
var keycode = E.keycode;
if (keycode = = 13) {
return false;
}
});
});
Click on the document
$ (document). Click (function (e) {
E.stoppropagation ();
var target = E.target,
Tagparent = $ (target). Parent (),
attr = $ (target,tagparent). Closest ('. Auto-tips ');
var tagcls = _config.targetcls.replace (/^\./, ");
if (Attr.length > 0 | | | $ (target,tagparent). Hasclass (Tagcls)) {
Return
}else {
$ ('. Auto-tips '). each (function (Index,item) {
!$ (item,tagparent). Hasclass (' hidden ') && $ (item,tagparent). addclass (' hidden ');
});
}
});
var stylesheet = '. auto-tips {margin:0 1px; List-style:none;height:auto!important;padding:0px;position:absolute; bord er:1px solid #ccc; top:27px; left:0; z-index:999; Width:100%;background: #fff!important;} ' +
'. Auto-tips p {overflow:hidden;margin:1px 0;padding:5px 5px;border-bottom:1px solid #e7e7e7; color: #666; text-decorati on:none;line-height:23px;white-space:nowrap;cursor:pointer;zoom:1;} ' +
'. Auto-tips p img{vertical-align:middle;float:left;} ' +
'. create-input{line-height:26px,padding-left:3px;} ' +
'. Create-input span{margin-top:1px;height:24px;float:left;} ' +
'. Create-input span i,.auto-tips span a{font-style:normal;float:left;cursor:default;} ' +
'. Create-input span a{padding:0 8px 0 3px;cursor:pointer;} ' +
'. Auto-tips P.HOVERBG {background-color: #669cb6; color: #fff; cursor:pointer;} ' +
'. hidden {display:none;} ';
This._addstylesheet (stylesheet);
},
/**
* Keyboard up and down key operation
*/
_keyupanddown:function (targetval,e,targetparent) {
var self = this,
_cache = Self.cache,
_config = Self.config;
If the request succeeds and returns the data (judged by the length of the element), do the following
if ($ ('. Auto-tips p ', targetparent) && $ ('. Auto-tips p ', targetparent). length > 0) {
var Plen = $ ('. Auto-tips p ', targetparent). Length,
KeyCode = E.keycode;
_cache.oldindex = _cache.currentindex;
Move Up action
if (keycode = = 38) {
if (_cache.currentindex = = 1) {
_cache.currentindex = plen-1;
}else {
_cache.currentindex = _cache.currentindex-1;
if (_cache.currentindex < 0) {
_cache.currentindex = plen-1;
}
}
if (_cache.currentindex!==-1) {
!$ (' auto-tips. P-index ' +_cache.currentindex,targetparent) hasclass (_CONFIG.HOVERBG) &&
$ ('. Auto-tips. P-index ' +_cache.currentindex,targetparent). addclass (_CONFIG.HOVERBG). Siblings (). RemoveClass (_ CONFIG.HOVERBG);
var curattr = $ ('. Auto-tips. P-index ' +_cache.currentindex,targetparent). attr (' data-html '),
Embid = $ ('. Auto-tips. P-index ' +_cache.currentindex,targetparent). attr (' embid ');
To determine whether a multiple-selection operation is a temporary left interface
if (_config.manyselect) {
_cache.inputarrs.push (CURATTR);
_cache.inputarrs = Self._unique (_cache.inputarrs);
Self._manyselect (targetparent);
}else {
$ (_config.targetcls,targetparent). Val (curattr);
Move up to add an attribute when you lose focus, judge if you have this attribute
if (!$ (_config.targetcls,targetparent). attr (' up ')) {
$ (_config.targetcls,targetparent). attr (' Up ', ' true ');
}
var pcls = $ (_config.targetcls,targetparent). closest (_CONFIG.PARENTCLS);
$ (_CONFIG.HIDDENCLS,PCLS). Val (embid);
Self._creatediv (targetparent,curattr);
self._closed (targetparent);
//Hover
Self._hover (targetparent);
}
}
}else if (keycode = = 40) {//Move Down operation
if (_cache.currentindex = = plen-1) {
_cache.currentindex = 0;
}else {
_cache.currentindex++;
if (_cache.currentindex > Plen-1) {
_cache.currentindex = 0;
}
}
if (_cache.currentindex!==-1) {
!$ (' auto-tips. P-index ' +_cache.currentindex,targetparent) hasclass (_CONFIG.HOVERBG) &&
$ ('. Auto-tips. P-index ' +_cache.currentindex,targetparent). addclass (_CONFIG.HOVERBG). Siblings (). RemoveClass (_ CONFIG.HOVERBG);
var curattr = $ ('. Auto-tips. P-index ' +_cache.currentindex,targetparent). attr (' data-html '),
Embid = $ ('. Auto-tips. P-index ' +_cache.currentindex,targetparent). attr (' embid ');
To determine whether a multiple-selection operation is a temporary left interface
if (_config.manyselect) {
_cache.inputarrs.push (CURATTR);
_cache.inputarrs = Self._unique (_cache.inputarrs);
Self._manyselect (targetparent);
}else {
$ (_config.targetcls,targetparent). Val (curattr);
Move down to add an attribute when you lose focus you judge if there is no this attribute
if (!$ (_config.targetcls,targetparent). attr (' down ')) {
$ (_config.targetcls,targetparent). attr (' Down ', ' true ');
}
var pcls = $ (_config.targetcls,targetparent). closest (_CONFIG.PARENTCLS);
$ (_CONFIG.HIDDENCLS,PCLS). Val (embid);
Self._creatediv (TARGETPARENT,CURATTR);
Self._closed (targetparent);
Hover
Self._hover (targetparent);
}
}
}else if (keycode = = 13) {//Enter operation
var curval = $ ('. Auto-tips. P-index ' +_cache.oldindex,targetparent). attr (' data-html ');
$ (_config.targetcls,targetparent). Val (Curval);
if (_config.isselecthide) {
!$ (". Auto-tips", targetparent). Hasclass (' hidden ') && $ (". Auto-tips", targetparent). addclass (' hidden ');
}
_cache.currentindex =-1;
_cache.oldindex =-1;
}
}
},
Key code judgment
_keycode:function (code) {
var arrs = [' 17 ', ' 18 ', ' 38 ', ' 40 ', ' 37 ', ' 39 ', ' 33 ', ' 34 ', ' 35 ', ' 46 ', ' 36 ', ' 13 ', ' 45 ', ' 44 ', ' 145 ', ' 19 ', ' 20 ', ' 9 '];
for (var i = 0, Ilen = arrs.length i < Ilen; i++) {
if (code = = Arrs[i]) {
return i;
}
}
return-1;
},
_dopostaction:function (targetval,targetparent) {
var self = this,
_cache = Self.cache,
_config = Self.config,
url = _config.url;
If the returned data is as follows:
var results = [{lastName: ' Tugenhua ', Emplid: ' E0987 ', Image: '},{lastname: ' Tugenhua ', Emplid: ' E0988 ', Image: '},{' LastName: ' Tugenhua ', Emplid: ' E0989 ', Image: '} ';
Self._renderhtml (results,targetparent);
Self._executeclick (results,targetparent);
/** $.get (url+ "? keyword=" +targetval+ "&timestamp=" +new Date (). GetTime (), function (data) {
var ret = $.parsejson (data.content),
results = Ret.results;
if (Results.length > 0) {
Self._renderhtml (results,targetparent);
Self._executeclick (results,targetparent);
}else {
!$ ('. Auto-tips ', targetparent). Hasclass (' hidden ') && $ ('. Auto-tips ', targetparent). addclass ("hidden");
$ ('. Auto-tips ', targetparent). html (');
}
});**/
},
_renderhtml:function (ret,targetparent) {
var self = this,
_config = Self.config,
_cache = Self.cache,
html = ';
for (var i = 0, Ilen = ret.length i < Ilen; i+=1) {
html = ' <p data-html = ' +ret[i].lastname+ ' (' +ret[i].emplid+ ') ' embid= ' ' +ret[i].emplid+ ' ' class= ' p-index ' +i+ ' > ' +
' <img src= ', ' +ret[i].image+ ' style= ' margin-right:5px, height= ' width= ' "title=" "alt=" ">"
' <span> ' +ret[i].lastname+ ' (' +ret[i].emplid+ ') </span> ' +
' </p> ';
}
Render values to the dropdown box.
$ ('. Auto-tips ', targetparent). HTML (HTML);
$ ('. Auto-tips ', targetparent). Hasclass (' hidden ') && $ ('. Auto-tips ', targetparent). Removeclass (' hidden ');
$ ('. Auto-tips p:last ', targetparent). css ({"Border-bottom": ' None '});
_config.renderhtmlcallback && $.isfunction (_config.renderhtmlcallback) && _ Config.renderhtmlcallback ();
The scroll bar calculates the length of P--whether the height of a p is greater than the height of the setting if the scroll bar appears instead
var Plen = $ ('. Auto-tips p ', targetparent). Length,
Pheight = $ ('. Auto-tips p ', targetparent). Height ();
if (_config.height > 0) {
if (Plen*pheight > _config.height) {
$ ('. Auto-tips ', targetparent). css ({' Height ': _config.height, ' overflow ': ' Auto '});
}else {
$ ('. Auto-tips ', targetparent). css ({' Height ': ' Auto ', ' overflow ': ' Auto '});
}
}
},
/**
* When the data is the same, click on the corresponding item to return the data
*/
_executeclick:function (ret,targetparent) {
var self = this,
_config = Self.config,
_cache = Self.cache;
$ ('. Auto-tips p ', targetparent). Unbind (' click ');
$ ('. Auto-tips p ', targetparent). bind (' click ', Function (e) {
var dataattr = $ (this). attr (' data-html '),
Embid = $ (this). attr (' embid ');
Decide whether to select multiple
if (_config.manyselect) {
_cache.inputarrs.push (DATAATTR);
_cache.inputarrs = Self._unique (_cache.inputarrs);
Self._manyselect (targetparent);
}else {
$ (_config.targetcls,targetparent). Val (dataattr);
var parentcls = $ (_config.targetcls,targetparent). Closest (_config.parentcls),
Hiddencls = $ (_CONFIG.HIDDENCLS,PARENTCLS);
$ (HIDDENCLS). Val (embid);
Self._creatediv (TARGETPARENT,DATAATTR);
Hover
Self._hover (targetparent);
!$ (_config.targetcls,targetparent). Hasclass (' hidden ') && $ (_config.targetcls,targetparent). addclass (' Hidden ');
}
Self._closed (targetparent);
if (_config.isselecthide) {
!$ ('. Auto-tips ', targetparent). Hasclass (' hidden ') && $ ('. Auto-tips ', targetparent). addclass (' hidden ');
}
_config.callback && $.isfunction (_config.callback) && _config.callback ();
});
Move the mouse over the effect
$ ('. Auto-tips p ', targetparent). Hover (function (e) {
!$ (this,targetparent). Hasclass (_CONFIG.HOVERBG) &&
$ (this,targetparent). addclass (_CONFIG.HOVERBG). Siblings (). Removeclass (_CONFIG.HOVERBG);
});
},
_hover:function (targetparent) {
$ ('. Create-input span ', targetparent). Hover (function () {
$ (this). CSS ({"Background": ' #ccc ', ' padding-left ': ' 0px '});
},function () {
$ (this). CSS ({"Background": "});
});
},
Create div tags dynamically hide input input box
_creatediv:function (targetparent,dataattr) {
var self = this,
_config = Self.config;
var iscreate = $ ('. Create-input ', targetparent);
Make sure you only create a div once
if (Iscreate.length > 0) {
$ ('. Create-input ', targetparent). Remove ();
}
$ (targetparent). Prepend ($ (' <div class= create-input "><span><i></i></span></div > '));
$ ('. Create-input span i ', targetparent). html (dataattr);
$ (_config.targetcls,targetparent). Val (dataattr);
$ ('. Create-input span ', targetparent). Append (' <a class= "ALink" >X</a> ");
$ ('. ALink ', Targetparent). css ({' float ': ' Left ', ' background ': ' None '});
},
X Shutdown Event
_closed:function (targetparent) {
var self = this,
_config = Self.config;
/*
* Click on the X Close button
* To determine if the current input box has up and down attributes are deleted or nothing done
*/
$ ('. ALink ', Targetparent). Click (function () {
$ ('. Create-input ', targetparent) && $ ('. Create-input ', targetparent). Remove ();
$ (_config.targetcls,targetparent) && $ (_config.targetcls,targetparent). Hasclass (' hidden ') &&
$ (_config.targetcls,targetparent). Removeclass (' hidden ');
$ (_config.targetcls,targetparent). Val (');
Empty the value of a hidden field
var curparent = $ (_config.targetcls,targetparent). closest (_CONFIG.PARENTCLS);
$ (_config.hiddencls,curparent). Val (');
var targetinput = $ (_config.targetcls,targetparent);
if ($ (targetinput). attr (' Up ') | | | $ (targetinput). attr (' down ')) {
$ (targetinput). attr (' Up ') && $ (targetinput)-removeattr (' Up ');
$ (targetinput). attr (' Down ') && $ (targetinput)-removeattr (' Down ');
}
_config.closedcallback && $.isfunction (_config.closedcallback) && _config.closedcallback ();
});
},
/*
* Array to repeat
*/
_unique:function (ARRS) {
var obj = {},
Newarrs = [];
for (var i = 0, Ilen = arrs.length i < Ilen; i++) {
if (Obj[arrs[i]]!= 1) {
Newarrs.push (Arrs[i]);
Obj[arrs[i]] = 1;
}
}
return newarrs;
},
/*
* Input Box Multi-select operation
*/
_manyselect:function (targetparent) {
var self = this,
_config = Self.config,
_cache = Self.cache;
if (_cache.inputarrs.length > 0) {
$ (_config.targetcls,targetparent). Val (_cache.inputarrs.join (', '));
}
},
/*
* To determine if it is a string
*/
_isstring:function (str) {
return Object.prototype.toString.apply (str) = = ' [Object String] ';
},
/*
* JS dynamic Add CSS style
*/
_addstylesheet:function (Refwin, csstext, id) {
var self = this;
if (self._isstring (Refwin)) {
id = csstext;
Csstext = Refwin;
Refwin = window;
}
Refwin = $ (Refwin);
var doc = document;
var Elem;
if (ID && (id = id.replace (' # ', ') ') {
Elem = $ (' # ' + ID, doc);
}
Add only once, not repeatedly
if (elem) {
Return
}
Elem = $ (' <style></style> '); Cannot create IE8 with bugs
Elem = document.createelement ("style");
Add to the DOM tree first, then assign a value to the Csstext, otherwise the CSS hack will fail
$ (' head ', doc). Append (Elem);
if (Elem.stylesheet) {//IE
Elem.styleSheet.cssText = Csstext;
else {//the Consortium
Elem.appendchild (Doc.createtextnode (csstext));
}
},
/*
* Destroy Operation Frees memory
*/
Destory:function () {
var self = this,
_config = Self.config,
_cache = Self.cache;
_cache.ret = [];
_cache.currentindex = 0;
_cache.oldindex = 0;
_cache.inputarrs = [];
_CONFIG.TARGETCLS = null;
}
};
Class
$ (function () {
var auto = new AutoComplete ({
URL: '/rocky/commonservice/user/find.json '
});
});