Autocomplete plug-in _ javascript in native js

Source: Internet
Author: User
This article mainly introduces information about how to implement the autocomplete plug-in native js. For more information about how to use the plug-in written by others in actual projects, to save time costs, some projects are urgent and you don't have enough time to write them on your own. Even if you write them, 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 p already exists, delete var parentNode = this. autoElement. parentNode | this. autoElement. parentElement; var childNodes = parentNode. childNodes; var showDiv = document. getElementById (this. config. showpId); if (showDiv) {parentNode. removeChild (showDiv);} // create the drop-down Div var p = document. createElement ('P'); p. id = this. config. showpId; // set the drop-down p style var style = this. config. style | {width: '200px ', height: 'auto', backgroundColor:' #1c5683 ', cursor: 'pointer', display: 'block '};
For (var prop in style) {p. style [prop] = style [prop];} this. showp = p ;}

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 ('P'); child. style. width = self. showp. 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. showp. appendChild (fragment); self. util. insertAfter (self. showp, self. autoElement); // Add a click event self for the drop-down box. util. addEvt (self. showp, '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 p appendChild: {}, /// append the display item closeDiv :{}, //// 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 drop-down p style setting url: '', // ajax request url paraName: 'name', // ajax Request Parameter select: function (){}, // The event triggered when the option is selected. showpId: ''// the id of the region selected from 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. addEv T (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 p already exists, delete var parentNode = this. autoElement. parentNode | this. autoElement. parentElement; var childNodes = parentNode. childNodes; var showDiv = document. getElement ById (this. config. showpId); if (showDiv) {parentNode. removeChild (showDiv);} // create the drop-down Div var p = document. createElement ('P'); p. id = this. config. showpId; // set the drop-down p style var style = this. config. style | {width: '200px ', height: 'auto', backgroundColor:' #1c5683 ', cursor: 'pointer', display: 'block '}; for (var prop in style) {p. style [prop] = style [prop];} this. showp = p ;}, // append the display item appendChild to the drop-down p: 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 ('P'); child. style. width = self. showp. 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. showp. appendChild (fragment); self. util. insertAfter (self. showp, self. autoElement); // Add a click event self for the drop-down box. util. addEvt (self. showp, '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; s Elf. closeDiv (); self. config. select. call (self, key, val) ;}, // close the closeDiv: function () {if (this. showp) {this. showp. 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 p // url: '', // url of the ajax request select: function (val, text) {alert (val + '---' + text) ;}, // event triggered when the option is selected, showpId: '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
 
  ();  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.

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.