Autocomplete plug-in implemented by native js and jsautocomplete plug-in
In actual projects, it is best to use plug-ins written by others to implement relevant functions. In order to save time costs, some projects are urgent and you do not have enough time to write them by yourself, even if you write it, you have to spend a lot of time debugging compatibility. However, for the purpose of learning, you can use your spare time to write and read some native js things and build plug-ins based on your own ideas.
When it comes to autotemplete, many people have used it and reference autotemplete. js, then you can prompt the drop-down option when entering a value in the input box, similar to the prompt function of the baidu search box. Next let's talk about our own ideas.
Add input events to the input box
1. The input event compatibility code is as follows:
AddEvt: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; } }
The input event is different from other events. Earlier versions of ie do not support input events. Only propertychange events can be used. Later versions of ie and w3c standard browsers support input events.
2. obtain data when an input event is triggered.
There are two types of data: an array of objects directly set, and an array of objects returned by an ajax request.
At this time, we need an ajax request function. Here we write a get request.
Get: function (url, paraobj, fn, timeout) {var xhr = null; try {// compatible with firefox, chrom if (window. XMLHttpRequest) {xhr = new XMLHttpRequest () ;}//// compatible with IE 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) ;}; var parastr = ''; parastr + = "? "; For (var prop in paraobj) {parastr + = prop +" = "+ paraobj [prop] +" & ";} xhr. open ('get', parastr! = "? "? (Url + parastr): url, true); xhr. send ();}
3. the ajax request is successful. When there is data, create a drop-down box and append options to the drop-down box. // create a drop-down Div
Code for creating a drop-down list:
CreateShowDiv: function () {// If the drop-down div already exists, delete var parentNode = this. autoElement. parentNode | this. autoElement. parentElement; var childNodes = parentNode. childNodes; var showDiv = document. getElementById (this. config. showdivId); if (showDiv) {parentNode. removeChild (showDiv);} // create the drop-down Div var div = document. createElement ('div '); div. id = this. config. showdivId; // set the drop-down div style var style = this. config. style | {width: '200px ', height: 'auto', backgroundColor:' #1c5683 ', cursor: 'pointer', display: 'block '}; <br> for (var prop in style) {div. style [prop] = style [prop];} this. showdiv = div ;}
Code for appending options:
AppendChild: function (data) {var self = this; var data = data; var fragment = document. createDocumentFragment (); for (var I = 0; I <data. length; I ++) {var obj = data [I]; var child = document. createElement ('div '); child. style. width = self. showdiv. style. width; child. style. border = '1px '; child. style. borderStyle = 'solid'; child. style. borderTopColor = 'white'; child. setAttribute ('key', obj [self. config. valueFiled]); child. innerHTML = obj [self. config. textFiled]; fragment. appendChild (child);} self. showdiv. appendChild (fragment); self. util. insertAfter (self. showdiv, self. autoElement); // Add a click event self for the drop-down box. util. addEvt (self. showdiv, 'click', function (e) {var evt = e | window. event; var target = evt. srcElement | evt.tar get; var key = target. getAttribute ("key"); var val = target. innerHTML; self. autoElement. value = val; self. closeDiv (); self. config. select. call (self, key, val );});}
The above describes the main steps. Now let's take a look at how to encapsulate the code into an object and make it a plug-in. In this case, we use the anonymous closure:
(Function (win) {var autocomplete = function () {this. init. apply (this, arguments);} autocomplete. prototype = {// Add the relevant operation code Init :{}, // initialize the parameter Render :{}, createShowDiv :{}, // create the drop-down div appendChild: {}, /// append the display item closeDiv :{} in the drop-down div, /// close the drop-down box ///// Tool Object, event, request, there is also the function util: {AddEvt :{}, // Add the event insertAfter :{}, /// append the element after an element get: {} // Ajax get request} win. autocomplete = function (paraobj) {new autocomplete (paraobj ). render () ;}}) (window)
After the code of the subject is added, the specific implementation code is displayed:
(Function (win) {var autocomplete = function () {this. init. apply (this, arguments);} autocomplete. prototype = {Init: function () {var args = Array. prototype. slice. call (arguments); if (args & args. length> 0) {var config = args [0]; var getType = Object. prototype. toString; if (config & getType. call (config) = "[object Object]") {// this. config = config; this. config = config | {id: '', // Control id Data: [], // data textFiled: '', // attribute name of the displayed text: valueFiled:'', // get the attribute name of the value. style :{}, // display the style setting url of the drop-down div: '', // url paraName: 'name' of the ajax request, // select: function (){}, // events triggered when the option is selected, showdivId: ''// id of the selected region in the drop-down list }}}, Render: function () {var self = this; if (self. config) {var autoElement = document. getElementById (self. config. id); this. autoElement = autoElement; if (autoElement) {self. util. A DdEvt (this. autoElement, 'input', function () {try {if (autoElement. value) {// ajax request to obtain data if (self. config. url &&! Self. config. data) {var paraobj = {}; paraobj [self. config. paraName] = autoElement. value; self. util. get (self. config. url, paraobj, function (data) {self. createShowDiv (); self. appendChild (eval ('+ data +') ;}, 10000) ;}/// directly set the form of an object array to else if (! Self. config. url & self. config. data) {self. createShowDiv (); self. appendChild (self. config. data) ;}} else {self. closeDiv () ;}} catch (e) {// TODO handle the exception alert (e) ;}}}}, /// create the drop-down Div createShowDiv: function () {// If the drop-down div already exists, delete var parentNode = this. autoElement. parentNode | this. autoElement. parentElement; var childNodes = parentNode. childNodes; var showDiv = document. getEleme NtById (this. config. showdivId); if (showDiv) {parentNode. removeChild (showDiv);} // create the drop-down Div var div = document. createElement ('div '); div. id = this. config. showdivId; // set the drop-down div style var style = this. config. style | {width: '200px ', height: 'auto', backgroundColor:' #1c5683 ', cursor: 'pointer', display: 'block '}; for (var prop in style) {div. style [prop] = style [prop];} this. showdiv = div;}, // in the drop-down list Append the display item appendChild: function (data) {var self = this; var data = data; var fragment = document. createDocumentFragment (); for (var I = 0; I <data. length; I ++) {var obj = data [I]; var child = document. createElement ('div '); child. style. width = self. showdiv. style. width; child. style. border = '1px '; child. style. borderStyle = 'solid'; child. style. borderTopColor = 'white'; child. setAttribute ('key', ob J [self. config. valueFiled]); child. innerHTML = obj [self. config. textFiled]; fragment. appendChild (child);} self. showdiv. appendChild (fragment); self. util. insertAfter (self. showdiv, self. autoElement); // Add a click event self for the drop-down box. util. addEvt (self. showdiv, 'click', function (e) {var evt = e | window. event; var target = evt. srcElement | evt.tar get; var key = target. getAttribute ("key"); var val = target. innerHTML; Self. autoElement. value = val; self. closeDiv (); self. config. select. call (self, key, val) ;}, // close the closeDiv: function () {if (this. showdiv) {this. showdiv. style. display = 'none' ;}}, util: {// Add event AddEvt: 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 ;}}, // append the insertAfter: function (ele, targetELe) {var parentnode = targetELe. parentNode | targetELe. parentElement; if (parentnode. lastChild = targetELe) {parentnode. appendChild (ele);} else {parentnode. insertBefore (ele, targetELe. nextSibling) ;}}, // Get request get: function (url, paraobj, 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) ;}; var parastr = ''; pa Rastr + = "? "; For (var prop in paraobj) {parastr + = prop +" = "+ paraobj [prop] +" & ";} xhr. open ('get', parastr! = "? "? (Url + parastr): url, true); xhr. send () ;}} win. autoComplete = function (paraobj) {new autocomplete (paraobj ). render () ;}}) (window)
The following code is used:
Page call
Window. onload = function () {AutoComplete ({id: 'txttest', // Control id url: '/Home/test4', // data paraName: 'name', textFiled: 'name', // attribute name of the displayed text: valueFiled: 'id', // get the attribute name of value // style :{}, // display the style settings of the drop-down div // url: '', // select: function (val, text) of the url requested by ajax) {alert (val + '---' + text) ;}, // The event triggered when the option is selected, showdivId: 'showdiv '// the id of the area selected from the drop-down list });});}
The background code is as follows. Here I use mvc
public JsonResult Test4(string name){ var list=new List<Student>(); list.Add(new Student { id="1",name="aaaaa"}); list.Add(new Student { id = "2", name = "aacc" }); list.Add(new Student { id = "3", name = "aabb" }); list.Add(new Student { id = "4", name = "bbcc" }); if (!string.IsNullOrEmpty(name)) { list = list.Where(p => p.name.Contains(name)).ToList(); } return Json(list,JsonRequestBehavior.AllowGet);}
Now that the basic functions and calls are complete, the process from the beginning to the end is quite troublesome. Every method is implemented step by step without referencing other libraries. The compatibility of various browsers should be taken into account.
The above is all the content of this article, hoping to help you learn.
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
- Compile the autoComplete plug-in native js