文档章节

jQuery AutoSuggest Plugin

lgscofield
 lgscofield
发布于 2015/06/26 13:58
字数 1873
阅读 17
收藏 0
点赞 0
评论 0

How It Works

AutoSuggest will turn any regular text input box into a rad auto-complete box. It will dynamically create all the HTML elements that it needs to function. You don't need to add any extra HTML to work with AutoSuggest. Also, AutoSuggest uses ZERO images! All styling is done 100% in the included CSS file. This means it is super easy to customize the look of everything! You only need to edit the included CSS file. You can even use images if you want, just add the appropriate lines of code into the CSS file.

As you type into the AutoSuggest input box, it will filter through it's Data and "suggest" matched Data items to you. You can pass in an Object of Data toAutoSuggest or you can have it call a URL as you type to get it's Data from.AutoSuggest will display the matched Data items in a selectable list, which is 100% customizable. You have the option of structuring the HTML elements of that list however you want via the formatList callback function. You case an example of this in the second example above.

When you type into the input box and the "suggestion" dropdown list appears, a few things happen:

  • class of "loading" is applied to the main AutoSuggest ul while the data is loaded. That class is then removed when all processing has finished and before the suggestion results list is made visible.
  • As you hover over each suggested option in the list a class of "selected" is added to that item, and then removed when you mouseout.
  • When you make a selection the item is added to the input box. Also there is a hidden input field generated for each AutoSuggest box that stores the values (comma separated) of each item you have selected. This input box will have a unique ID as well as a class name of "as-values".

The plugin expects the Data passed into it (or gathered from the URL) to be formatted in JSON. JSON is an extremely easy format to work with, and if you don't already... you should :) To learn more about JSON, check out my post/video, An Introduction to JSON.

When an AJAX request is made the search string is sent over in a param named "q" by default. However you can change that name with the queryParam option. Here is a default example AJAX request: http://www.mysite.com/your/script/?q=mick
"mick" would be the search query that was typed into the input box. Be sure to setup your server-side code to grab that param and send back some results.

As of AutoSuggest version 1.4 you can now create selections by using the tab orcomma keys. To do this simply type something into the box and hit the tab orcomma keys. The selection is added to AutoSuggest in the exact same manner as if it were chosen from the Results dropdown.

AutoSuggest has been tested (and works) in: IE7 & IE8, Firefox, Safari, Opera, and Chrome.

How To Use It

Obviously you need to make sure you have the latest jQuery library (at least 1.3) already loaded in your page. After that it's really simple, just add the following code to your page (make sure to wrap your code in jQuery's ready function):

$(function(){
$("input[type=text]").autoSuggest(data);
});

The above line of code will apply AutoSuggest to all text type input elements on the page. Each one will be using the same set of Data. If you want to have multipleAutoSuggest fields on your page that use different sets of Data, make sure you select them separately. Like this:

$(function(){
$("div.someClass input").autoSuggest(data);
$("#someID input").autoSuggest(other_data);
});

Doing the above will allow you to pass in different options and different Data sets.

Below is an example of using AutoSuggest with a Data Object and other various options:

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};
$("input[type=text]").autoSuggest(data.items, {selectedItemProp: "name", searchObjProps:"name"});

Below is an example using a URL to gather the Data Object and other various options:

$("input[type=text]").autoSuggest("http://mysite.com/path/to/script", {minChars: 2, matchCase: true});

Please not that you MUST have an object property of "value" for each data item. (This is now configureable with the selectedValuesProp option). The "value" property will be stored (comma separated) in the hidden input field when chosen from the "suggestion" dropdown list. You can see an example of the "value" property being set for each data item in the example above. Typically the "value" property would contain the ID of the item, so you can send a list of "chosen" IDs to your server.

Below is an example of how to process the data sent via AJAX to your server in PHP:

<?
$input $_GET["q"];
$data array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Options

  • asHtmlIDstring (false by default) - Enables you to specify your own custom ID that will be appended to the top level AutoSuggest UL element's ID name. Otherwise it will default to using a random ID. Example: id="CUSTOM_ID". This is also applies to the hidden input filed that holds all of the selected values. Example: id="as-values-CUSTOM_ID"
  • startTextstring ("Enter Name Here" by default) - Text to display when the AutoSuggest input field is empty.
  • emptyTextstring ("No Results" by default) - Text to display when their are no search results.
  • preFillobject or string (empty object by default) - Enables you to pre-fill the AutoSuggest box with selections when the page is first loaded. You can pass in a comma separated list of values (a string), or an object. When using a string, each value is used as both the display text on the selected item and for it's value. When using an object, the options selectedItemProp will define the object property to use for the display text and selectedValuesProp will define the object property to use for the value for the selected item. Note: you must setup your preFill object in that format. A preFill object can look just like the example objects laid out above.
  • limitTextstring ("No More Selections Are Allowed" by default) - Text to display when the number of selections has reached it's limit.
  • selectedItemPropstring ("value" by default) - Name of object property to use as the display text for each chosen item.
  • selectedValuesPropstring ("value" by default) - Name of object property to use as the value for each chosen item. This value will be stored into the hidden input field.
  • searchObjPropsstring ("value" by default) - Comma separated list of object property names. The values in these objects properties will be used as the text to perform the search on.
  • queryParamstring ("q" by default) - The name of the param that will hold the search string value in the AJAX request.
  • retrieveLimitnumber (false by default) - If set to a number, it will add a '&limit=' param to the AJAX request. It also limits the number of search results allowed to be displayed in the results dropdown box.
  • extraParamsstring ("" by default) - This will be added onto the end of the AJAX request URL. Make sure you add an '&' before each param.
  • matchCasetrue or false (false by default) - Make the search case sensitive when set to true.
  • minCharsnumber (1 by default) - Minimum number of characters that must be entered into the AutoSuggest input field before the search begins.
  • keyDelaynumber (400 by default) - Number of milliseconds to delay after a keydown on the AutoSuggest input field and before search is started.
  • resultsHighlighttrue or false (true by default) - Option to choose whether or not to highlight the matched text in each result item.
  • neverSubmittrue or false (false by default) - If set to true this option will never allow the 'return' key to submit the form that AutoSuggest is a part of.
  • selectionLimitnumber (false by default) - Limits the number of selections that are allowed to be made to the number specified.
  • showResultListtrue or false (true by default) - If set to false, the Results Dropdown List will never be shown at any time.
  • startcallback function - Custom function that is run only once on each AutoSuggest field when the code is first applied.
  • selectionClickcallback function - Custom function that is run when a previously chosen item is clicked. The item that is clicked is passed into this callback function as 'elem'.
    Example: selectionClick: function(elem){ elem.fadeTo("slow", 0.33); }
  • selectionAddedcallback function - Custom function that is run when a selection is made by choosing one from the Results dropdown, or by using the tab/comma keys to add one. The selection item is passed into this callback function as 'elem'.
    Example: selectionAdded: function(elem){ elem.fadeTo("slow", 0.33); }
  • selectionRemovedcallback function - Custom function that is run when a selection removed from the AutoSuggest by using the delete key or by clicking the "x" inside the selection. The selection item is passed into this callback function as 'elem'.
    Example: selectionRemoved: function(elem){ elem.fadeTo("fast", 0, function(){ elem.remove(); }); }
  • formatListcallback function - Custom function that is run after all the data has been retrieved and before the results are put into the suggestion results list. This is here so you can modify what & how things show up in the suggestion results list.
  • beforeRetrievecallback function - Custom function that is run right before the AJAX request is made, or before the local objected is searched. This is used to modify the search string before it is processed. So if a user entered "jim" into the AutoSuggest box, you can call this function to prepend their query with "guy_". Making the final query = "guy_jim". The search query is passed into this function. Example: beforeRetrieve: function(string){ return string; }
  • retrieveCompletecallback function - Custom function that is run after the ajax request has completed. The data object MUST be returned if this is used. Example: retrieveComplete: function(data){ return data; }
  • resultClickcallback function - Custom function that is run when a search result item is clicked. The data from the item that is clicked is passed into this callback function as 'data'.
    Example: resultClick: function(data){ console.log(data); }
  • resultsCompletecallback function - Custom function that is run when the suggestion results dropdown list is made visible. Will run after every search query.

The formatList option will hand you 2 objects:

  • data: This is the data you originally passed into AutoSuggest (or retrieved via an AJAX request)
  • elem: This is the HTML element you will be formatting (the 'result' li item).

 

In order to add extra things to the 'result' item (like an image) you will need to make sure you pass that data into  AutoSuggest .
Below is an example of formatList in action:

 

formatList: function(data, elem){
var my_image = data.image;
var new_elem = elem.html("add/change stuff here, put image here, etc.");
return new_elem;
}

You MUST return the HTML object. formatList will run on each 'result' item.

本文转载自:http://lgscofield.iteye.com/blog/1679474

共有 人打赏支持
lgscofield

lgscofield

粉丝 20
博文 105
码字总数 63036
作品 0
南京
架构师
dabeng/OrgChart

Native JavaScript(ES6) Version Web Components Version Foreword First of all, thanks a lot for wesnolte's great work -- jOrgChart. The thought that using nested tables to build o......

dabeng ⋅ 06/07 ⋅ 0

jQuery学习笔记--选择器和事件

以下内容参考 W3school 简书 你要是问我什么是jQuery 那可以这么两句话概括: jQuery 是一个 JavaScript 库。 jQuery 极大地简化了 JavaScript 编程。 要学jQuery最好有点javaScript的基础 ...

codingcoge ⋅ 05/17 ⋅ 0

JavaWeb05-HTML篇笔记(一)

1.1上次课内容回顾: JQuery: JQuery的概述:是一个轻量级的JavaScript的类库.对JS进行封装. 常见的JS的框架: JQuery的使用: JQuery的选择器:(*) JQuery实现效果: JQuery样式操作: JQuer...

我是小谷粒 ⋅ 05/10 ⋅ 0

Zepto.js 简介(第一章)

Zepto.js 简介(第一章) 在做C端-H5的时候,很多时候会用到Zepto.js,所以在这里,我就把它整理一下。 什么是Zepto zepto是轻量级的JavaScript库,专门为移动端定制的框架 与jquery有着类似...

张靖bibibi ⋅ 06/19 ⋅ 0

【每天一个JQuery特效】淡入淡出显示或隐藏窗口

我是JQuery新手爱好者,有时间就练练代码,防止手生,争取每天一个JQuery练习,在这个博客记录下学习的笔记。 本特效主要采用fadeIn()和fadeOut()方法显示淡入淡出的显示效果显示或隐藏元...

Rhymo-Wu ⋅ 06/18 ⋅ 0

jQuery中,html、val与text的区别与联系

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书 本文主要介绍如何使用jQuery中的html(),text()和val()三种方法,用于读取、修改元素的html结构,元素的文本内容,以及表单元素的value值...

quincuntial ⋅ 2016/11/22 ⋅ 0

vue获取input输入框的数据

用惯了jQuery,突然使用vue感觉很不习惯,有很多不同的地方,感觉是两个不同的思想来写前端的代码。jQuery是使用选择器($)选取DOM对象,对其进行赋值、取值、事件绑定等操作。而Vue则是通过...

王子城 ⋅ 前天 ⋅ 0

jQuery函数attr()和prop()的区别

在jQuery中,attr()函数和prop()函数都用于设置或获取指定的属性,它们的参数和用法也几乎完全相同。 但不得不说的是,这两个函数的用处却并不相同。下面我们来详细介绍这两个函数之间的区别...

Apirl ⋅ 05/16 ⋅ 0

Python自动化开发学习17-jQuery

jQuery学习之前 jQuery 是 JavaScript 的一个类库,类似 python 中的模块。 jQuery在线手册:http://jquery.cuishifeng.cn/ 官网:http://jquery.com/ 版本选择 目前jQuery有三个大版本:1.x...

骑士救兵 ⋅ 前天 ⋅ 0

强大的JQuery-自定义插件

====jQuery插件编写原则===== 1.命名 jQuery..js 2.插件内部,this指向的是当前选择器取得的JQuery对象,不是内部对象, 例如click(), 内部的this指向的是DOM元素 3.this.each可以遍历所有元素...

chengfei_liu ⋅ 05/25 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

6.1 压缩打包介绍 6.2 gzip压缩工具 6.3 bzip2压缩工具 6.4 xz压缩工具

压缩打包介绍 使用压缩工具的好处: 使用压缩文件,不仅可以节省磁盘空间,而且在传输时还能节省网络宽带。 我们通常讲的家用宽带和机房宽带100M是有区别的: 机房宽带的上行和下行都是100M,...

Linux_老吴 ⋅ 32分钟前 ⋅ 0

SpringBoot热部署加持

概述 进行SpringBoot的Web开发过程中,我们很多时候经常需要重启Web服务器才能保证修改的 源代码文件、或者一些诸如xml的配置文件、以及一些静态文件生效,这样耗时又低效。所谓的热部署指的...

CodeSheep ⋅ 39分钟前 ⋅ 0

OSChina 周六乱弹 —— 假如你被熊困到树上

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @小小编辑:推荐歌曲《如果写不出好的和弦就该在洒满阳光的钢琴前一起吃布丁》 《如果写不出好的和弦就该在洒满阳光的钢琴前一起吃布丁》- 谢...

小小编辑 ⋅ 今天 ⋅ 5

vbs 取文件大小 字节

dim namedim fs, s'name = Inputbox("姓名")'msgbox(name)set fs = wscript.createobject("scripting.filesystemobject") 'fs为FSO实例if (fs.folderexists("c:\temp"))......

vga ⋅ 今天 ⋅ 1

高并发之Nginx的限流

首先Nginx的版本号有要求,最低为1.11.5 如果低于这个版本,在Nginx的配置中 upstream web_app { server 到达Ip1:端口 max_conns=10; server 到达Ip2:端口 max_conns=10; } server { listen ...

算法之名 ⋅ 今天 ⋅ 0

Spring | IOC AOP 注解 简单使用

写在前面的话 很久没更新笔记了,有人会抱怨:小冯啊,你是不是在偷懒啊,没有学习了。老哥,真的冤枉:我觉得我自己很菜,还在努力学习呢,正在学习Vue.js做管理系统呢。即便这样,我还是不...

Wenyi_Feng ⋅ 今天 ⋅ 0

博客迁移到 https://www.jianshu.com/u/aa501451a235

博客迁移到 https://www.jianshu.com/u/aa501451a235 本博客不再更新

为为02 ⋅ 今天 ⋅ 0

win10怎么彻底关闭自动更新

win10自带的更新每天都很多,每一次下载都要占用大量网络,而且安装要等得时间也蛮久的。 工具/原料 Win10 方法/步骤 单击左下角开始菜单点击设置图标进入设置界面 在设置窗口中输入“服务”...

阿K1225 ⋅ 今天 ⋅ 0

Elasticsearch 6.3.0 SQL功能使用案例分享

The best elasticsearch highlevel java rest api-----bboss Elasticsearch 6.3.0 官方新推出的SQL检索插件非常不错,本文一个实际案例来介绍其使用方法。 1.代码中的sql检索 @Testpu...

bboss ⋅ 今天 ⋅ 0

informix数据库在linux中的安装以及用java/c/c++访问

一、安装前准备 安装JDK(略) 到IBM官网上下载informix软件:iif.12.10.FC9DE.linux-x86_64.tar放在某个大家都可以访问的目录比如:/mypkg,并解压到该目录下。 我也放到了百度云和天翼云上...

wangxuwei ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部