JS imitation Baidu search automatic prompt box matching query function _javascript skills

Source: Internet
Author: User

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.

The following code:

Copy Code code as follows:



<div class= "Parentcls" >


<div style= "width:200px;height:26px;border:1px solid #ccc;" >


<input type= "text" class= "Inputelem" style= "width:200px;height:26px;line-height:26px"; />


</div>


<input type= "hidden" class= "Hiddencls"/>


</div>


<div class= "Parentcls" >
<div style= "width:200px;height:26px;border:1px solid #ccc;" >
<input type= "text" class= "Inputelem" style= "width:200px;height:26px;line-height:26px"; />
</div>
<input type= "hidden" class= "Hiddencls"/>
</div>

3. There are multiple input boxes on the support page.

4. Support mouse click and keyboard move up and down key operation similar to Baidu input box.
All the labels on the page are generated dynamically, and no additional tags are required. As above only need input label other DIV tags do not rely on only the parent element to add Class "Parentcls" (Of course you can configure the class name),
and add a Class "Hiddencls" to the hidden field input box that you want to pass to the background developer. Of course, you can also configure parameters automatically.

The demand for my fuzzy query matching is this:
1. Each keyup time clicks or the keyboard moves down moves the operation input box fills the user name/the work number hidden domain fills the work number sends requests the server to return the data to render. Of course, the hidden field fill the value is the form forms submission time backstage to get the work number submitted, so need a hidden domain.
2. When the user directly entered the value of the input box and did not move down the keyboard or click a drop-down box when the mouse loses focus (blur) The current input box values are empty hidden field values are empty, the purpose of this is to prevent the data from being submitted by the last form from being persisted in the hidden domain When the user re-enter the user also does not operate the keyboard up or down operation or click the action and then click the Submit button (lost focus), then the value is empty hidden field value is empty so as to prevent the search out is not the user input that dongdong.
3. When the user clicks on an item or moves up and down, the input box dynamically generates a value and the input box value cannot be entered again until you click on the input box x to re-enter it.
4. The existing input box can be selected more than the interface is currently not perfect input box multiple selection operation.
5. Suppress Ctrl + V or right button paste operation.

The following HTML code is as follows:

Copy Code code as follows:



&lt;div class= "Parentcls" &gt;


&lt;div style= "width:200px;height:26px;border:1px solid #ccc;" &gt;


&lt;input type= "text" class= "Inputelem" style= "width:200px;height:26px;line-height:26px"; /&gt;


&lt;/div&gt;


&lt;input type= "hidden" class= "Hiddencls"/&gt;


&lt;/div&gt;


<div class= "Parentcls" >
<div style= "width:200px;height:26px;border:1px solid #ccc;" >
<input type= "text" class= "Inputelem" style= "width:200px;height:26px;line-height:26px"; />
</div>
<input type= "hidden" class= "Hiddencls"/>
</div>

<input type= "button" value= "Submit"/>

The JS code is as follows:

Copy Code code as follows:



/**


* 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) &amp;&amp; $ (_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 ($ (' &lt;div class= "auto-tips hidden" &gt;&lt;/div&gt; "));


$ ('. 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 &gt;-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 &gt; 0 | | | $ (target,tagparent). Hasclass (Tagcls)) {


Return


}else {


$ ('. Auto-tips '). each (function (Index,item) {


!$ (item,tagparent). Hasclass (' hidden ') &amp;&amp; $ (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 &lt; 0) {


_cache.currentindex = plen-1;


}


}


if (_cache.currentindex!==-1) {





!$ (' auto-tips. P-index ' +_cache.currentindex,targetparent) hasclass (_CONFIG.HOVERBG) &amp;&amp;


$ ('. 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 &gt; Plen-1) {


_cache.currentindex = 0;


}


}


if (_cache.currentindex!==-1) {

!$ (' auto-tips. P-index ' +_cache.currentindex,targetparent) hasclass (_CONFIG.HOVERBG) &amp;&amp;


$ ('. 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 ') &amp;&amp; $ (". 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 &lt; 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+ "&amp;timestamp=" +new Date (). GetTime (), function (data) {


var ret = $.parsejson (data.content),


results = Ret.results;


if (Results.length &gt; 0) {


Self._renderhtml (results,targetparent);


Self._executeclick (results,targetparent);


}else {


!$ ('. Auto-tips ', targetparent). Hasclass (' hidden ') &amp;&amp; $ ('. 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 &lt; Ilen; i+=1) {


html = ' &lt;p data-html = ' +ret[i].lastname+ ' (' +ret[i].emplid+ ') ' embid= ' ' +ret[i].emplid+ ' ' class= ' p-index ' +i+ ' &gt; ' +


' &lt;img src= ', ' +ret[i].image+ ' style= ' margin-right:5px, height= ' width= ' "title=" "alt=" "&gt;"


' &lt;span&gt; ' +ret[i].lastname+ ' (' +ret[i].emplid+ ') &lt;/span&gt; ' +


' &lt;/p&gt; ';


}


Render values to the dropdown box.


$ ('. Auto-tips ', targetparent). HTML (HTML);


$ ('. Auto-tips ', targetparent). Hasclass (' hidden ') &amp;&amp; $ ('. 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 &gt; 0) {


if (Plen*pheight &gt; _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 ') &amp;&amp; $ (_config.targetcls,targetparent). addclass (' Hidden ');


}


Self._closed (targetparent);


if (_config.isselecthide) {


!$ ('. Auto-tips ', targetparent). Hasclass (' hidden ') &amp;&amp; $ ('. Auto-tips ', targetparent). addclass (' hidden ');


}


_config.callback &amp;&amp; $.isfunction (_config.callback) &amp;&amp; _config.callback ();


});

Move the mouse over the effect


$ ('. Auto-tips p ', targetparent). Hover (function (e) {


!$ (this,targetparent). Hasclass (_CONFIG.HOVERBG) &amp;&amp;


$ (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 &gt; 0) {


$ ('. Create-input ', targetparent). Remove ();


}


$ (targetparent). Prepend ($ (' &lt;div class= create-input "&gt;&lt;span&gt;&lt;i&gt;&lt;/i&gt;&lt;/span&gt;&lt;/div &gt; '));


$ ('. Create-input span i ', targetparent). html (dataattr);


$ (_config.targetcls,targetparent). Val (dataattr);


$ ('. Create-input span ', targetparent). Append (' &lt;a class= "ALink" &gt;X&lt;/a&gt; ");


$ ('. 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) &amp;&amp; $ ('. Create-input ', targetparent). Remove ();


$ (_config.targetcls,targetparent) &amp;&amp; $ (_config.targetcls,targetparent). Hasclass (' hidden ') &amp;&amp;


$ (_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 ') &amp;&amp; $ (targetinput)-removeattr (' Up ');


$ (targetinput). attr (' Down ') &amp;&amp; $ (targetinput)-removeattr (' Down ');


}


_config.closedcallback &amp;&amp; $.isfunction (_config.closedcallback) &amp;&amp; _config.closedcallback ();


});


},


/*


* Array to repeat


*/


_unique:function (ARRS) {


var obj = {},


Newarrs = [];


for (var i = 0, Ilen = arrs.length i &lt; 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 &gt; 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 = $ (' &lt;style&gt;&lt;/style&gt; '); 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 '


});


});


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.