Native JS Write AutoComplete plug-in _javascript skills

Source: Internet
Author: User

The

has recently been mentioning too much about the dropdown option, want to enter the keyword, you can search the content of the demand, but before the project too rush, so there is no time to do, because you want to use the original JS to write some content, so plug-ins are used in the original JS write the idea of the following
the first step: Fninit Implementation initializes some fields
step two: to load the search box div
Step three: implement search, delete the original node and load the new node
Step Fourth: set value
code when clicked or enter:
Autocomplete.js

/** * @summary autocomplete * @description input box automatically retrieves drop-down options * @version 0.0.1 * @file autocomplete.js * @auth 
 or Cangowu * @contact 1138806090@qq.com * @copyright Copyright 2016 CANGOWU. * This is a native JS based on the automatic completion of the search of the Drop-down input box, * can be moved by the mouse up and down key to enter and directly with the mouse click to select the search options, in some key places have comments * * examples see: * CSDN Blog: http://blog.cs dn.net/wzgdjm/article/details/51122615 * github:https://github.com/cangowu/autocomplete * * (function () {FU Nction AutoComplete () {if (!) ( 
    This instanceof AutoComplete)} {return to New AutoComplete (); 
    } this.ssearchvalue = '; 
  This.index =-1; } Autocomplete.prototype = {fninit:function (option) {//Initialize basic information var odefault = {id: ',//Control I D data: [],//paraname: ', textfiled: ',///display of the text attribute name valuefiled: ',//Get property of value Name style: {},//The style setting URL of the Drop-down div displayed: ',//ajax requested URL select:function () {},//When selecting option triggered by 
   event};   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 amount divID//judge if the URL is passed in, no data is passed in, Ajax is fetched, otherwise the data is used 
        F (this.surl!== ' && this.aData.length = = 0) {var = this; 
          This.util.fnGet (This.surl, function (data) {Console.log (eval (data)); 
        That.adata = eval (data); 
      }, 10); 
      ///To Adata sort var Stextfield = this.stextfiled; 
   This.aData.sort (function (A, b) {return A[stextfield] > B[stextfield];   }); 
      Gets the control This.dominput = document.getElementById (THIS.SID); 
    This.domdiv = document.getElementById (This.sdivid); 
      }, Fnrender:function () {//render some of the required nodes var that = this; 
        Generates a corresponding div that hosts some of the options below 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); 
      After loading, the domdiv can be assigned to This.domdiv = document.getElementById (This.sdivid); //Add KeyUp event that.util.fnAddEvent to input (that.dominput, ' KeyUp ', function (event) {That.fnsearch (E 
      VENT); 
    }); Fnsearch:function (Event) {//Judge if it is not the ENTER key, perform a search if (Event.keycode!=&& event.keycode!= && event.keycode!=) {this.fnloadsearchcontent (); 
      This.fnshowdiv (); 
        else {///After Search monitor keyboard event var length = This.domDiv.children.length; 
          if (Event.keycode = =) {++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 = =) {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 =) {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 search value This.ssearchvalue = this.domInput.value; Select exit var strimsearchvalue = This.sSearchValue.replace (/(^\s*) If the value is empty | ( 
      \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>")//Search for bold character display 
          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.styl E.display = This.domDiv.style.display = = ' None '? 
      ' Block ': ' None '; }, Util: {//public interface Method Fninsertafter:function (Ele, Targetele) {var parentnode = Targetele.paren Tnode | | 
        Targetele.parentelement; 
        if (Parentnode.lastchild = = Targetele) {parentnode.appendchild (ele); 
        else {Parentnode.insertbefore (ele, targetele.nextsibling); }, Fnaddevent:function (Ele, EVT, fn) {if (Document.addeventlistener) {ele.addevent 
        Listener (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"); 
        The catch (e) {//todo handle the exception xhr = new ActiveXObject (' microsoft.xmlhttp '); } Xhr.onreadystatechange = function () {if (this.readystate = = 4 && this.status = 20 
          0) {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 the entire content of this article, I hope to learn JavaScript program to help you.

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.