Compile autoComplete plug-in native js and autocomplete in js
Recently, when there are too many drop-down options, you need to enter keywords to search for the content. However, the project was too busy, so there was no time to do it, because I want to write some content using native js, the idea of writing the plug-in using native js is as follows:
Step 1:FnInit implements initialization of some fields
Step 2:Load the div in the search box
Step 3:Implement the search function. Delete the original node and load the new node.
Step 4:Set value when you click or press Enter.
Code:
AutoComplete. js
/*** @ Summary AutoComplete * @ description the drop-down option is automatically retrieved from the input box * @ version 0.0.1 * @ file autoComplete. js * @ author cangowu * @ contacts 1138806090@qq.com * @ copyright Copyright 2016 cangoWu. ** this is a drop-down box for automatically completing search based on native js. * You can move the mouse up or down and press enter and directly click * to select the search option, in some key areas there are comments ** example see: * CSDN blog: http://blog.csdn.net/wzgdjm/article/details/51122615 * Github: https://github.com/cangowu/autoComplete **/(function () {fun Ction AutoComplete () {if (! (This instanceof AutoComplete) {return new AutoComplete ();} this. sSearchValue = ''; this. index =-1;} AutoComplete. prototype = {fnInit: function (option) {// initialize the basic information var oDefault = {id: '', // Control id data: [], // data paraName: '', textFiled:'', // property name of the displayed text: valueFiled: '', // attribute name of the retrieved value style :{}, // The style setting url of the displayed drop-down div is '', // select: function () {}, // event triggered when the ajax request url is selected }; var _ option = option; t His. sId = _ option. id | oDefault. id; this. aData = _ option. data | oDefault. data; this. paraName = _ option. paraName | oDefault. paraName; this. sTextFiled = _ option. textFiled | oDefault. textFiled; this. sValueFiled = _ option. valueFiled | oDefault. valueFiled; this. style = _ option. style | oDefault. style; this. sUrl = _ option. url | oDefault. url; this. fnSelect = _ option. select | oDefault. select; this. SDivId = this. sId + new Date (). getTime (); // load option divid // determine if the url is passed in and no data is passed in, ajax will get the data; otherwise, data will be used to get the data if (this. sUrl! = ''& This. aData. length = 0) {var that = this; this. util. fnGet (this. sUrl, function (data) {console. log (eval (data); that. aData = eval (data) ;}, 10) ;}// sort var sTextField = this For aData. sTextFiled; this. aData. sort (function (a, B) {return a [sTextField]> B [sTextField] ;}); // obtain the control this. domInput = document. getElementById (this. sId); // this. domDiv = document. getElementById (this. sDivId);}, fnRende R: function () {// render some required node var that = this; // generate a corresponding div that carries the if (that. sDivId) {var domDiv = document. createElement ('div '); domDiv. id = that. sDivId; domDiv. style. background = '# fff'; domDiv. style. width = that. domInput. offsetWidth-2 + 'px '; domDiv. style. position = 'absolute '; domDiv. style. border = '1px solid # a9a9a9 '; domDiv. style. display = 'none'; that. util. fnInsertAfter (domDiv, that. dom Input); // The domDiv value can be assigned to this only after loading. domDiv = document. getElementById (this. sDivId);} // Add the keyup event to the input that. util. fnAddEvent (that. domInput, 'keyup', function (event) {that. fnSearch (event) ;}) ;}, fnSearch: function (event) {// determines if it is not the Enter key, perform the search if (event. keyCode! = 13 & event. keyCode! = 38 & event. keyCode! = 40) {this. fnLoadSearchContent (); this. fnShowDiv ();} else {// monitor the keyboard event var length = this after searching. domDiv. children. length; if (event. keyCode = 40) {++ this. index; if (this. index> = length) {this. index = 0;} else if (this. index = length) {this. domInput. value = this. sSearchValue;} this. domInput. value = this. domDiv. childNodes [this. index]. text; this. fnChangeClass ();} else if (event. keyCode = 38) {th Is. index --; if (this. index <=-1) {this. index = length-1;} else if (this. index =-1) {this. obj. value = this. sSearchValue;} this. domInput. value = this. domDiv. childNodes [this. index]. text; this. fnChangeClass ();} else if (event. keyCode = 13) {this. fnLoadSearchContent (); this. fnShowDiv (); // this. domDiv. style. display = this. domDiv. style. display = 'none '? 'Block': 'none'; this. index =-1;} else {this. index =-1 ;}}, fnLoadSearchContent: function () {// delete all child nodes while (this. domDiv. hasChildNodes () {this. domDiv. removeChild (this. domDiv. firstChild);} // set the search value this. sSearchValue = this. domInput. value; // if the value is null, exit var sTrimSearchValue = this. sSearchValue. replace (/(^ \ s *) | (\ s * $)/g, ''); if (sTrimSearchValue =" ") {this. domDiv. style. display = 'None'; return;} try {var reg = new RegExp ("(" + sTrimSearchValue + ")", "I") ;}catch (e) {return ;} // search for and add a new node var nDivIndex = 0; for (var I = 0; I <this. aData. length; I ++) {if (reg. test (this. aData [I] [this. sTextFiled]) {var domDiv = document. createElement ("div"); // div. className = "auto_onmouseout"; domDiv. text = this. aData [I] [this. sTextFiled]; domDiv. onclick = this. fnSetValue (this); domD Iv. onmouseover = this. fnAutoOnMouseOver (this, nDivIndex); domDiv. innerHTML = this. aData [I] [this. sTextFiled]. replace (reg, "<strong> $1 </strong>"); // this is displayed in bold. domDiv. appendChild (domDiv); nDivIndex ++ ;}}, fnSetValue: function (that) {return function () {that. domInput. value = this. text; that. domDiv. style. display = 'none' ;}}, fnAutoOnMouseOver: function (that, idx) {return function () {th At. index = idx; that. fnChangeClass () ;}}, fnChangeClass: function () {var that = this; var length = that. domDiv. children. length; for (var j = 0; j <length; j ++) {if (j! = That. index) {that. domDiv. childNodes [j]. style. backgroundColor = ''; that. domDiv. childNodes [j]. style. color = '# 000';} else {that. domDiv. childNodes [j]. style. backgroundColor = 'Blue '; that. domDiv. childNodes [j]. style. color = '# fff' ;}}, fnShowDiv: function () {if (this. domDiv. children. length! = 0) {this. domDiv. style. display = this. domDiv. style. display = 'none '? 'Block': 'none'; }}, util: {// public interface method fnInsertAfter: function (ele, targetEle) {var parentnode = targetEle. parentNode | targetEle. parentElement; if (parentnode. lastChild = targetEle) {parentnode. appendChild (ele);} else {parentnode. insertBefore (ele, targetEle. nextSibling) ;}}, fnAddEvent: function (ele, evt, fn) {if (document. addEventListener) {ele. addEventListener (evt, fn, false);} else If (document. attachEvent) {ele. attachEvent ('on' + (evt = "input "? "Propertychange": evt), fn);} else {ele ['on' + (evt = "input "? "Propertychange": evt)] = fn ;}, fnGet: function (url, fn, timeout) {var xhr = null; try {if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else if (Window. activeXObject) {xhr = new ActiveXObject ("Msxml2.Xmlhttp") ;}} catch (e) {// TODO handle the exception xhr = new ActiveXObject ('Microsoft. xmlhttp ');} xhr. onreadystatechange = function () {if (this. readyState = 4 & this. status = 200) {fn. call (this, this. responseText);} else {setTimeout (function () {xhr. abort () ;}, timeout) ;}; xhr. open ('get', url, true); xhr. send () ;}} window. autoComplete = function (option) {var aOption = Array. prototype. slice. call (arguments); for (var I = 0; I <aOption. length; I ++) {var autoComplete = new AutoComplete (); autoComplete. fnInit (aOption [I]); autoComplete. fnRender () ;}}) (window );
Index.html
<! DOCTYPE html>
Data. json
[ { "id": "1", "name": "aaaaa" }, { "id": "2", "name": "bbbbb" }, { "id": "3", "name": "ccccc" } ]
The above is all the content of this article, and I hope it will help you learn javascript programming.
Articles you may be interested in:
- JS control autocomplete 0.11 demo and download updated on January 1, January 5
- Autocomplete Textbox Example javascript is automatically completed
- Javascript automatically completes AutoComplete (Ajax query)
- Jquery. AutoComplete. js Chinese revision (firefox supported)
- Jquery-based text box and autocomplete (asp.net + json)
- When the autocomplete component is introduced, JS reports a String constant error that has not ended.
- A simple Autocomplete Automatic completion example implemented by JS
- Autocomplete plug-in implemented by native js