Recently, when there are too many drop-down options, I hope to enter keywords to search for content, but the project was too rush before, so I didn’t have time to do it because I hope to write some content with native js, so the plug-in uses native js to write the following idea
Step 1: fnInit implementation initializes 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 clicking or entering
Code:
autoComplete.js
/** * @summary AutoComplete * @description The input box automatically retrieves the drop-down option* @version 0.0.1 * @file autoComplete.js * @author cangowu * @contact [email protected] * @copyright Copyright 2016 cangoWu. * This is a drop-down input box that automatically completes search based on native js. * You can press the mouse up and down keys and click directly with the mouse* Select the search option, and there are comments in some key places* * Examples are: * CSDN blog: http://blog.csdn.net/wzgdjm/article/details/51122615 * Github: https://github.com/cangowu/autoComplete * */ (function () { function AutoComplete() { if (!(this instanceof AutoComplete)) { return new AutoComplete(); } this.sSearchValue = ''; this.index = -1; } AutoComplete.prototype = { fnInit: function (option) {//Initialize basic information var oDefault = { id: '', //Control id data: [], //Data paraName: '', textFiled: '', //Attribute name of the displayed text valueFiled: '', //Get the attribute name of the value style: {}, //Style setting of the drop-down div displayed url: '', //Ajax requested url select: function () { }, //Event triggered when selecting options}; var _option = option; this.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 //Judge that if a url is passed in and no data data is passed in, ajax gets the data. Otherwise, use data to fetch 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 aData var sTextField = this.sTextFiled; this.aData.sort(function (a, b) { return a[sTextField] > b[sTextField]; }); //Get the control this.domInput = document.getElementById(this.sId); //This.domDiv = document.getElementById(this.sDivId); }, fnRender: function () {//Render some necessary nodes var that = this; //Generate a corresponding div, hosting some subsequent options 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.domInput); //Only DOMDiv can be assigned to this.domDiv = document.getElementById(this.sDivId); } //Add keyup event to input that.util.fnAddEvent(that.domInput, 'keyup', function (event) { that.fnSearch(event); }); }, fnSearch: function (event) { //Judge if it is not the Enter key, perform a search when up and down the key if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40) { this.fnLoadSearchContent(); this.fnShowDiv(); } else {//Monitor keyboard events after search var length = this.domDiv.children.length; if (event.keyCode == 40) { ++this.index; if (this.index >= length) { this.index = 0; } else if (this.index == length) { this.index == length) { this.domInput.value = this.sSearchValue; } this.domInput.value = this.domDiv.childNodes[this.index].text; this.fnChangeClass(); } else if (event.keyCode == 38) { this.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 empty, select to 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 and add 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); domDiv.onmouseover = this.fnAutoOnMouseOver(this, nDivIndex); domDiv.innerHTML = this.aData[i][this.sTextFiled].replace(reg, "<strong>$1</strong>");//The searched characters show this.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 () { that.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> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input type="text" id="txtTest"> </div> <br> <div> <input type="text" id="txtTest1"> </div> <script src="autoComplete.js"></script> <script> window.onload = function () { var option = { id: 'txtTest', //Control id data: [{ "id": "1", "name": "aaaaa" }, { "id": "2", "name": "bbbbbb" }, { "id": "2", "name": "bbbWu bb" }, { "id": "2", "name": "bbbzbb" }], paraName: 'name', textFiled: 'name', //The attribute name of the displayed text Filed: 'id', //Get the attribute name of the value of the value select: function (val, text) { alert(val + '' + text); } //Event triggered when selecting an option}; var option1 = { id: 'txtTest1', //Control id url: 'data.json', //Data paraName: 'name', textFiled: 'name', //Attribute name of the displayed text Filed: 'id', //Get the attribute name of the value of the value select: function (val, text) { alert(val + '' + text); } //Event triggered when selecting an option}; AutoComplete(option,option1); } </script> </body> </html>data.json
[ { "id": "1", "name": "aaaaa" }, { "id": "2", "name": "bbbbb" }, { "id": "3", "name": "cccccc" } ]The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.