本文转自:https://github.com/tcrosen/twitter-bootstrap-typeahead

使用升级版的 Bootstrap typeahead  v1.2.2

http://www.cnblogs.com/haogj/p/3378508.html

How to Use JSON Objects With Twitter Bootstrap Typeahead

http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/

Twitter’s Bootstrap is all the rage these days, and for good reason. It’s chock full of aesthetically pleasing, easily customizable styles and useful widgets. Among the latter you’ll find typeahead, a widget for auto-suggesting possible values in response to user input.

Typeahead Using an Array of Strings

Bootstrap’s standard implementation of typeahead uses an array of strings to provide suggestions:

html:

1
2
3
<body>
   <input id="search"/>
</body>

JavaScript:

1
2
3
var colors = ["red", "blue", "green", "yellow", "brown", "black"];
$('#search').typeahead({source: colors});

Here’s what the widget looks like:

The implementation is simple, clean, and works as expected. What more could you want?

Typeahead Using an Array of Objects

Well, sometimes working with strings is too limiting. For example, consider a scenario where you want the user to enter a US state and you need to capture the two-letter state abbreviation once the selection is made (if the user enters “California”, you’ll store “CA”):

To build this feature we could use an array of objects which contain both the name of the state and the abbreviation:

1
2
3
4
5
6
7
8
var stateList = [
    {"stateCode": "CA", "stateName": "California"},
    {"stateCode": "AZ", "stateName": "Arizona"},
    {"stateCode": "NY", "stateName": "New York"},
    {"stateCode": "NV", "stateName": "Nevada"},
    {"stateCode": "OH", "stateName": "Ohio"},
   ...
];

Bootstrap exposes a set of overridable options we can leverage to implement typeahead with an array of objects:

  1. Source
  2. Matcher
  3. Sorter
  4. Highlighter
  5. Updater

It’s important to note that you can probably leverage Bootstrap’s own implementations for pretty much everything except source and updater. That said, in this example, we will implement all of them using the template below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$('#search').typeahead({
    source: function (query, process) {
        // implementation
    },
    updater: function (item) {
        // implementation
    },
    matcher: function (item) {
        // implementation
    },
    sorter: function (items) {
        // implementation
    },
    highlighter: function (item) {
       // implementation
    },
});

1. Source

Let’s begin with source. This option specifies the data set to use for the auto-suggest list. It can take either an array of strings (which we saw in the first example) or a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
source: function (query, process) {
    states = [];
    map = {};
    var data = [
        {"stateCode": "CA", "stateName": "California"},
        {"stateCode": "AZ", "stateName": "Arizona"},
        {"stateCode": "NY", "stateName": "New York"},
        {"stateCode": "NV", "stateName": "Nevada"},
        {"stateCode": "OH", "stateName": "Ohio"}
    ];
    $.each(data, function (i, state) {
        map[state.stateName] = state;
        states.push(state.stateName);
    });
    process(states);
},

This function takes two parameters: query and process (I’ll talk about both in a bit). The first thing we do is get data, an array of state objects. Though I’ve hardcoded contents of data inside the function in this example, in a real production app it would come from the server.

Next, we map state names to the corresponding objects using two global variables, map and states. This is necessary because Bootstrap needs a list of strings to actually display auto suggestions (states array), while we need to get the original objects (stored in the map). Obviously, names of your objects need to be unique for this to work.

Finally, we call Bootstrap’s process() function with the states array. Process() orchestrates the event loop for typeahead (by calling matcher, sorter, etc) and sets up the auto-suggest list displayed to the user.

You may have also noticed that we didn’t use query input parameter in this example. Typically, query would be used to implement server-side filtering of the auto-suggestion list because it contains the search string entered by the user.

2. Matcher

Next, let’s implement the matcher(). This function is used by Bootstrap to check if the search string typed by the user matches anything in the source list. Its purpose is to filter the auto-suggest list to only the relevant values:

1
2
3
4
5
matcher: function (item) {
    if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
        return true;
    }
}

The implementation above is fairly trivial. We simply take user’s input (contained in this.query) and check to see if it exists anywhere in the item. Conversion of both strings to lower case is needed because the user is unlikely to expect case to be considered when matching terms.

3. Sorter

The Sorter function is responsible for sorting the list of suggestions filtered by the matcher:

1
2
3
sorter: function (items) {
    return items.sort();
}

Again, I should note that my implementation is quite simplistic. Sorting suggestions is usually a more elaborate affair. For example, Bootstrap’s own implementation considers whether user input is found at the beginning of the suggested string and whether the match was case sensitive.

4. Highlighter

Bootstrap uses highlighter to highlight user’s input within auto-suggested results. We can use a simple regex match to find and bold user’s input:

1
2
3
4
highlighter: function (item) {
    var regex = new RegExp( '(' + this.query + ')', 'gi' );
    return item.replace( regex, "<strong>$1</strong>" );
}

5. Updater

Finally, we get to the updater. This function is called by Bootstrap once the user selects an item, which gives us a chance to do something with the selection. In this case, we’d like to record the selected state abbreviation in a global variable selectedState before returning the item:

1
2
3
4
updater: function (item) {
    selectedState = map[item].stateCode;
    return item;
}

Note of caution: it’s very important that you return the item because that’s the value used by Bootstrap to set the input box.

References:

https://github.com/twitter/bootstrap/pull/3682

http://twitter.github.com/bootstrap/javascript.html#typeahead

Bootstrap 3 Typeahead相关推荐

  1. 【Bootstrap】 typeahead自动补全

    typeahead 这篇文章记录了我在使用typeahead的一些问题,不是很全,但是基本够用. Bootstrap提供typeahead组件来完成自动补全功能. 两种用法: 直接给标签添加属性 &l ...

  2. 30 个惊艳的 Bootstrap 扩展插件

    2019独角兽企业重金招聘Python工程师标准>>> Bootstrap 是快速开发Web应用程序的前端工具包.它是一个CSS和HTML的集合,它使用了最新的浏览器技术,给你的We ...

  3. 分享Python采集100个jQuery代码,总有一款适合您

    分享Python采集100个jQuery代码,总有一款适合您 Python采集的100个jQuery代码下载链接:https://pan.baidu.com/s/1hSBJKIU_jgBrmPTrvA ...

  4. Bootstrap typeahead自动补全插件的坑

    ##Bootstrap typeahead 插件的坑 typeahead 自动补全插件, 还是先简单记录一下,如何使用吧: <div class="form-group"&g ...

  5. Bootstrap typeahead使用问题记录及解决方案

    简单介绍 Bootstrap typeahead插件是用来完成输入框的自动完成.模糊搜索和建议提示的功能,支持ajax数据加载,类似于jquery的流行插件Autocomplete. typeahea ...

  6. BootStrap学习2 typeahead

    首先看看这些 http://www.wrapcode.com/bootstrap/typeahead-json-objects/ http://stackoverflow.com/questions/ ...

  7. 第五章 使用 Bootstrap Typeahead 组件(百度下拉效果)

    推荐链接:http://www.cnblogs.com/haogj/p/3376874.html UnderScore官网:http://underscorejs.org/ 参考文档:http://w ...

  8. bootstrap typeahead实现模糊查询功能

    一:下载并引用 <script type="text/javascript" src="assets/js/bootstrap-typeahead.js" ...

  9. Bootstrap 简洁、直观、强悍、移动设备优先的前端开发框架,让web开发更迅速、简单。...

    http://v3.bootcss.com/ 从2.x升级到3.0版本 Bootstrap 3并不向后兼容Bootstrap v2.x.下面章节列出的内容可以作为从v2.x升级到v3.0的通用指南.如 ...

最新文章

  1. 常用快捷键整理,提升工作效率!
  2. oracle如何给表上锁,【ORACLE】Oracle中发生表加锁、死锁的原因,查看,与解决方法...
  3. 将java项目传输到centos7服务端
  4. mysql中怎样扑抓到是那个字段出错_mysql 常见的几个错误问题
  5. “萝莉变大妈”事件系主播策划!斗鱼出拳:永久封停!
  6. PAIP.ASP技术手册
  7. 草根站长的你是感觉自豪还是苦逼
  8. ifonts下载ttf字体文件
  9. 信息安全原理复习资料
  10. mysql表删除后恢复
  11. 使用python模块 将中文大写汉字转化成阿拉伯数字
  12. 【WeNews】三胞债务重组方案出炉 650亿元金融债务如何化解
  13. 13.深入浅出:负反馈放大电路稳定性(自激振荡)——参考《模拟电子技术基础》清华大学华成英主讲
  14. 深度强化学习——DQN
  15. thinkphp5常用函数汇总_(thinkPHP)PHP常用函数大全
  16. ArrayDeque(双端队列的线性实现)详解
  17. 错误“无法找到XXX.exe的调试信息,或者调试信息不匹配。未使用调试信息生成二进制文件“的解决方案
  18. Procreate绘画教程
  19. AZC低压智能电力电容解决用电三相不平衡,提高功率因数
  20. 【最新版】Java学习路线(含B站口碑推荐视频链接)

热门文章

  1. 在控制台显示sql语句,类似hibernate show_sql.
  2. ClickOnce 部署概述
  3. Java TCP/IP Socket 编程 笔记
  4. Weblogic下创建JMS消息服务
  5. ant design中的栅格化系统
  6. 572. Subtree of Another Tree
  7. 迅为I.MX6Q开发板配不同分辨率不同尺寸液晶屏幕
  8. RabbitMQ 上手记录-part 1-基础概念
  9. '无法将“vue”项识别为 cmdlet、函数、脚本文件或可运行程序的名称' 或 'vue不是内部或外部命令' 的解决方法...
  10. BZOJ 3208: 花神的秒题计划Ⅰ