Benefits to ~ Share a smart tip control based on jquery intellseach.js

Source: Internet
Author: User

First, the demand

We often encounter "in-site search" needs, in order to improve the user experience, we hope to do like Baidu's instant intelligence tips. For example: A company personnel Management system, want to search Li xx, as long as the input "Li", the system will naturally prompt some employees surnamed Li, so that user-friendly use. Plainly speaking, is the user input, the system will prompt the relevant results, or, when the user clicked the search box, recommended some content, such as 360, Baidu will prompt today's main news or search volume of large content.

jquery already has a plugin like this, called AutoComplete, but I don't think it's a good idea. There are a lot of introductions about AutoComplete, and interested friends can try.

Look at the title to know, this is just to share a plugin, will not discuss the background search related algorithms and procedures, that is, the background returns a specific format of data, the control is responsible for rendering the result rendering. OK, first look at:

Effect One:

  

Two:

  

The style is independent of the control and requires only one input text.

Second, parameter description

The control is in JSON format as a transport format. Parameters more, most of them have default values (specific to see source), some may not be used, keep the default. As follows:

URL: request address. such as: Handler.ashx, the background to obtain the data address

Property: The properties of the JSON object to display. If we go directly to ["Tom", "Tom Cat", "tom2"] such a form, then this property can not be set, but sometimes we will return [{"Name": "Tom", "id": "001"},{"name": "Tom Cat", "id": " 002 "},{" name ":" Tom2 "," ID ":" 003 "}] in this form, the name is displayed, then the property is set to" name ". As for the ID of the item we want to click on when clicked, click on the event.

ItemNumber: The number of items displayed.

isemptyrequest: When focus, blank is the request is initiated. As I said earlier, if you click on the search box (there is nothing at this time), you want to recommend something, set this property to True, and the request will be initiated.

defaultvalue: Default value. Usually it will be: "Please enter keywords ..." This kind of hint.

Width: drop-down list widths.

aligner: The element to align.

maxheight: Maximum height. If you set this height, the scroll bar appears when you exceed it.

Ajax: {
Timeout: timeout period
cache: Whether caching
},

Event:{
SetData: triggered before sending a request. Used to set parameters
ItemClick: Click on item to trigger
Enterkeydown: Press the ENTER key to trigger
BeforeRender: Triggers before all items are rendered
Endrender: Triggers after all items are rendered
Itembeforerender: Triggers before item rendering
Itemafterrender: Triggers after item rendering
Beforesend: triggered before sending a request. User settings request header parameters, etc., equivalent to jquery Ajax beforesend.
}

The methods in the event are triggered at the appropriate time, and it is important to note that all methods receive a parameter, which is an object, has 4 properties, and, in some cases, is empty if the property is not. Include the following properties:

Jthis:input's JQuery object.

Jitem: The JQuery object for the item.

Data: The JSON string returned. If the return JSON needs to be processed at the foreground, it can be obtained through the Data property, and the JSON string will need to return after processing is complete.

Event: Events object, such as event object when you press ENTER.

Iii. examples

Examples of Use:

    $ ("#search"). Intellsearch ({        URL: "Handler.ashx", Property        : "Name",        itemnumber:5,        isemptyrequest: False,        defaultvalue: "Please enter keywords ...",                width:$ ("#search"). Width () + 2,        maxheight:-1,        event:{            Itemclick:function (obj) {                alert (Obj.item.ID);            },            enterkeydown:function (obj) {                if (Obj.item) {                    alert ("With current item");                } else{                    alert ("No current Item");}}}        );

Iv. Summary

If you still have your own logic to handle, you also support chaining calls, which can be written like this $ ("#search"). Intellsearch ({Parameters ...}). Focus (function () {Your handling ...});

Sharing this plugin is intended to help friends in need, mainly for learning. Because it is v1.0, there may be some bugs, found friends can also tell me, I will amend in time.

Attached source code

JS Code

/* Search Smart Hint v1.0 date:2015.09.08 */;(function (w,$) {$.fn.intellsearch = function (options) {var jthis = this; var _dftopts = {url: "",//Request address or array property: "",//properties of the JSON object to display it emnumber:5,//shows the number of bars isemptyrequest:false,//focus whether the blank initiated the request DefaultValue: "",//Default value width:0,//column                Table width aligner:jthis,//the element to be aligned maxheight:-1,//the maximum height ajax:{ timeout:3000,//timeout cache:true//Cache}, event:{/* parameter description: parameter:{jth is: "JQ input", Jitem: "JQ item", Data: "JSON result", Event: "Event"}*/setdata:null,//set parameters ITEMCL                ick:null,//hit Item trigger enterkeydown:null,//press ENTER to trigger beforerender:null,//all items are triggered before rendering                endrender:null,//all items are rendered after the triggering itembeforerender:null,//item is rendered before triggering the itemafterrender:null,//item rendering Beforesend:nullTrigger before sending a request}};        $.extend (_dftopts,options); if (!_dftopts.url) {throw Error ("URL cannot be empty!        ");                        } var Jresult;                var _value = "";        var _ajax = _dftopts.ajax;        var _event = _dftopts.event;        var _cache = []; var _focuscount = 0;//Prevents focus triggering multiple times (Sogou)/*on window*/window.intellobj = Window.intellobj | | {}; /*for global event*/Window.intelldocumentclick = Window.intelldocumentclick | |            Function (e) {if (!window.intellobj.jthis) {return;            } if (E.target!== window.intellobj.jthis[0]) {setintellobj (null); }} window.intelldocumentkeydown = Window.intelldocumentkeydown | |            Function (e) {var jthis = window.intellObj.jthis;            if (!jthis) {return;            } var code = E.keycode;                var value = Window.intellObj.value;        var Jresult,jcuritem,keyword;                if (code = = = | | code = = = +) {Jresult = Window.intellObj.jResult;                Jitems = Jresult.find ("Li");                Jcuritem = Jresult.find ("Li.cur");                    if (code = = =) {if (Jcuritem.length > 0) {jcuritem.click ();                                               }else{setintellobj (NULL);                        if (_event.enterkeydown) {_event.enterkeydown ({"Jthis": Jthis, "event": E});                }} jthis.blur ();                            }else if (jitems.length > 0) {if (code = = =) {if (jcuritem.length <= 0) {                            Jcuritem = Jitems.last ();                            Jcuritem.addclass ("cur");                        Keyword = Jcuritem.text ();                     }else{       var index = Jcuritem.index ();                            Jcuritem.removeclass ("cur");                                                        if (index <= 0) {keyword = value;                                }else{Jcuritem = Jitems.eq (index-1);                                Jcuritem.addclass ("cur");                            Keyword = Jcuritem.text ();                    }} jthis.val (keyword);                            }else{if (jcuritem.length <= 0) {Jcuritem = Jitems.first ();                            Jcuritem.addclass ("cur");                        Keyword = Jcuritem.text ();                            }else{var index = Jcuritem.index ();                            Jcuritem.removeclass ("cur"); if (index + 1 >= jitems.length) {keYword = value;                                }else{Jcuritem = Jitems.eq (index+1);                                Jcuritem.addclass ("cur");                            Keyword = Jcuritem.text ();                    }} jthis.val (keyword);        }}}}/*event handler*/$.fn.unintell = function () {remove ();                   } $ (document). Unbind ({Click:window.intelldocumentclick,keydown:window.intelldocumentkeydown})        . bind ({click:window.intelldocumentclick,keydown:window.intelldocumentkeydown});            Jthis.focus (function () {_focuscount++;            if (_focuscount > 1) {return;            } if (Window.intellObj.jthis && jthis!== window.intellObj.jthis) {setintellobj (null);            } var keyword = attrValue (); if (keyword = = = _dftoptS.defaultvalue) {keyword = "";            AttrValue (keyword);            } if (keyword | | _dftopts.isemptyrequest) {sendrequest ();            }}) Jthis.blur (function () {_focuscount = 0;            if (!attrvalue ()) {attrValue (_dftopts.defaultvalue);                }}) Jthis.keyup (function (e) {if (E.keycode = = = | | e.keycode = = 40) {            Return            } var keyword = attrValue ();                if (!keyword) {remove ();                Window.intellObj.value = _value = "";            Return                } if (keyword!== _value) {window.intellObj.value = _value = keyword;            SendRequest ();                }        });                return Initbox ();            /*function*/function Initbox () {attrValue (_dftopts.defaultvalue);        return jthis;        }        function Initintell () {Generate ();            Register ();        Setintellobj ({jthis:jthis,jresult:jresult});            } function Generate () {var offset = _dftopts.aligner.offset (); var width = _dftopts.width?            _dftopts.width: _dftopts.aligner.width ();            Jresult = $ ("<ul>", {"Class": "Intellresult"});            Jresult.width (width). css ({"position": "Absolute", "left": Offset.left, "top": Offset.top + Jthis.outerheight ()});            $ ("Body"). Append (Jresult);            if (_dftopts.maxheight > 0) {jresult.height (_dftopts.maxheight). CSS ("Overflowy", "scroll");                }} function Remove () {if (Jresult) {jresult.remove ();            Jresult = null;                }} function register () {Jresult.on ("click", "Li", function () {var Jitem = $ (this);                var index = Jitem.index (); var keyword = JiteM.text ();                                AttrValue (keyword);                                _value = keyword;                if (_event.itemclick) {_event.itemclick ({"Jthis": Jthis, "Jitem": Jitem, "item": _cache[index]}); }}). On ("MouseEnter", "Li", function () {$ (this). Siblings ("Li"). Removeclass ("cur"). End (). ADDCL            ("cur");            }). On ("MouseLeave", "Li", and function () {$ (this). Removeclass ("cur");        });                    } function Setintellobj (obj) {if (!obj) {if (Window.intellObj.jResult) {                Window.intellObj.jResult.remove ();                } window.intellObj.jthis = null;            Window.intellObj.jResult = null;                }else{window.intellObj.jthis = obj.jthis;            Window.intellObj.jResult = Obj.jresult;            }} function SendRequest () {var data;            if (_event.setdata) {                    data = _event.setdata ({"Jthis": Jthis});                } $.ajax ({url:_dftopts.url, data:data, Cache:_ajax.cache,                        Timeout:_ajax.timeout, Beforesend:function (XHR) {if (_event.beforesend) {                    _event.beforesend (XHR);                    }}, Success:function (data) {remove ();                ShowData (data);        }, error:null});            } function ShowData (data) {data = $.trim (data)? $.parsejson (data): data;                if (_event.beforerender) {var rs = _event.beforerender ({"Jthis": Jthis, "Data":d ATA});                if (rs = = = False) {return;                } if (rs!== undefined) {data = rs;            }} if (!data) {return;    }        var Jitem,ja,jspan,hasprop,item,text,othertexts,isrender,index; var list = $.isarray (data)?            Data: [Data];            var length = List.length; Length = length > _dftopts.itemnumber?            _dftopts.itemnumber:list.length;            if (length <= 0) {return;            } Initintell ();            _cache.length = 0;            Hasprop = List[0][_dftopts.property];                for (Var i=0;i<length;i++) {item = List[i];                if (item = = = NULL | | item = = = undefined) {continue; } Text = Hasprop?                Item[_dftopts.property]: item;                Text = $.trim (text.tostring ());                if (Text = = = "") {continue;                } Jitem = $ ("<li>", {"Class": "Intellresult_item"});                JA = $ ("<a>", {"title": Text}). AppendTo (Jitem);                Jspan = $ ("<span>"). AppendTo (JA); Index= Text.tolowercase (). IndexOf (_value.tolowercase ());                Othertexts = Splittext (Text,_value,index);                    if (othertexts) {Jspan.text (Text.substr (index,_value.length));                        if (Othertexts.length > 1) {$ ("<b>", {"text": Othertexts[0]}). insertbefore (Jspan);                    $ ("<b>", {"text": Othertexts[1]}). InsertAfter (Jspan); }else{if (index = = = 0) {$ ("<b>", {"text": Othertexts[0]}). insertafte                        R (Jspan);                        }else{$ ("<b>", {"text": Othertexts[0]}). insertbefore (Jspan);                }}}else{Jspan.text (text);                } Isrender = true; if (_event.itembeforerender) {Isrender = _event.itembeforerender ({"Jthis": Jthis, "Jitem": Jitem, "item": ITE                m});   }             if (Isrender!== false) {jresult.append (jitem);                    if (_event.itemafterrender) {_event.itemafterrender ({"Jthis": Jthis, "Jitem": Jitem, "Item": item});            }} _cache.push (item);            } if (_event.endrender) {_event.endrender ({"Jthis": Jthis});        } jresult.show (); } function AttrValue (value) {if (!value && value! = "") {return $.trim (Jthis.val ()            );        } jthis.val (value);            } function Splittext (text,value,index) {var tlength = text.length;            var vlength = value.length;            if (index = =-1) {return null;                } if (index = = = 0) {if (index + vlength >= tlength) {return null;            } return [Text.substr (index + vlength)];        }    if (index + vlength >= tlength) {return [Text.substr (0,index)];        } return [Text.substr (0,index), TEXT.SUBSTR (index + vlength)]; }}) (Window,jquery);

Style

. Intellresult{margin:0;padding:0;background: #fff; border:1px solid #b6b6b6; clear:both;z-index:999;display:none;}. Intellresult li{margin:0;padding:0;padding:5px 15px;height:20px;line-height:20px;overflow:hidden;text-overflow: Ellipsis;cursor:pointer;white-space:nowrap;}. Intellresult li.cur{background: #E5E0E0;}

Benefits to ~ Share a smart tip control based on jquery intellseach.js

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.