使用typeahead js 做quick search

js references :

[Handlebar]

http://handlebarsjs.com/

[typeahead]

https://twitter.github.io/typeahead.js/

demo html :

<script src="jquery-1.11.1.min.js"></script>
<script src="typeahead.bundle.js"></script>
<script src="handlebars-v1.3.0.js"></script>
<p>
1.Basic
</p>

<div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>

<script>

var substringMatcher_basic = function(strs) {
  return function findMatches(q, cb) {
    var matches, substrRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, ‘i‘);

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push({ value: str });
      }
    });

    cb(matches);
  };
};

var _data_states_basic = [‘Alabama‘, ‘Alaska‘, ‘Arizona‘, ‘Arkansas‘, ‘California‘,
  ‘Colorado‘, ‘Connecticut‘, ‘Delaware‘, ‘Florida‘, ‘Georgia‘, ‘Hawaii‘,
  ‘Idaho‘, ‘Illinois‘, ‘Indiana‘, ‘Iowa‘, ‘Kansas‘, ‘Kentucky‘, ‘Louisiana‘,
  ‘Maine‘, ‘Maryland‘, ‘Massachusetts‘, ‘Michigan‘, ‘Minnesota‘,
  ‘Mississippi‘, ‘Missouri‘, ‘Montana‘, ‘Nebraska‘, ‘Nevada‘, ‘New Hampshire‘,
  ‘New Jersey‘, ‘New Mexico‘, ‘New York‘, ‘North Carolina‘, ‘North Dakota‘,
  ‘Ohio‘, ‘Oklahoma‘, ‘Oregon‘, ‘Pennsylvania‘, ‘Rhode Island‘,
  ‘South Carolina‘, ‘South Dakota‘, ‘Tennessee‘, ‘Texas‘, ‘Utah‘, ‘Vermont‘,
  ‘Virginia‘, ‘Washington‘, ‘West Virginia‘, ‘Wisconsin‘, ‘Wyoming‘
];

$(‘#the-basics .typeahead‘).typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: ‘states‘,
  displayKey: ‘value‘,
  source: substringMatcher_basic(_data_states_basic)
});

</script>

<p>
2.Using Bloodhound
</p>

<div id="bloodhound">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>

<script>

var _data_states_bloodhound = [‘Alabama‘, ‘Alaska‘, ‘Arizona‘, ‘Arkansas‘, ‘California‘,
  ‘Colorado‘, ‘Connecticut‘, ‘Delaware‘, ‘Florida‘, ‘Georgia‘, ‘Hawaii‘,
  ‘Idaho‘, ‘Illinois‘, ‘Indiana‘, ‘Iowa‘, ‘Kansas‘, ‘Kentucky‘, ‘Louisiana‘,
  ‘Maine‘, ‘Maryland‘, ‘Massachusetts‘, ‘Michigan‘, ‘Minnesota‘,
  ‘Mississippi‘, ‘Missouri‘, ‘Montana‘, ‘Nebraska‘, ‘Nevada‘, ‘New Hampshire‘,
  ‘New Jersey‘, ‘New Mexico‘, ‘New York‘, ‘North Carolina‘, ‘North Dakota‘,
  ‘Ohio‘, ‘Oklahoma‘, ‘Oregon‘, ‘Pennsylvania‘, ‘Rhode Island‘,
  ‘South Carolina‘, ‘South Dakota‘, ‘Tennessee‘, ‘Texas‘, ‘Utah‘, ‘Vermont‘,
  ‘Virginia‘, ‘Washington‘, ‘West Virginia‘, ‘Wisconsin‘, ‘Wyoming‘
];

var states_bloodhound = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace(‘value‘),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: $.map(_data_states_bloodhound, function(state) { return { value: state }; })
});

// kicks off the loading/processing of `local` and `prefetch`
states_bloodhound.initialize();

$(‘#bloodhound .typeahead‘).typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: ‘states‘,
  displayKey: ‘value‘,
  // `ttAdapter` wraps the suggestion engine in an adapter that
  // is compatible with the typeahead jQuery plugin
  source: states_bloodhound.ttAdapter()
});

</script>

<p>
3. Pre-fetch (need to replace json URL)
</p>

<div id="prefetch">
  <input class="typeahead" type="text" placeholder="Countries">
</div>

<script>
var prefetch_countries = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace(‘name‘),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  limit: 10,
  prefetch: {
    url: ‘your json url here‘,
    filter: function(list) {
      return $.map(list, function(country) { return { name: country }; });
    }
  }
});

// kicks off the loading/processing of `local` and `prefetch`
prefetch_countries.initialize();

// passing in `null` for the `options` arguments will result in the default
// options being used
$(‘#prefetch .typeahead‘).typeahead(null, {
  name: ‘prefetch_countries‘,
  displayKey: ‘name‘,
  // `ttAdapter` wraps the suggestion engine in an adapter that
  // is compatible with the typeahead jQuery plugin
  source: prefetch_countries.ttAdapter()
});

</script>

<p>4.Custom Template</p>

<style>
#custom-templates .empty-message {
  padding: 5px 10px;
 text-align: center;
}

</style>

<div id="custom-templates">
  <input class="typeahead" type="text" placeholder="Oscar winners for Best Picture">
</div>

<script>
var _data_states_template_countries = [‘Alabama‘, ‘Alaska‘, ‘Arizona‘, ‘Arkansas‘, ‘California‘,
  ‘Colorado‘, ‘Connecticut‘, ‘Delaware‘, ‘Florida‘, ‘Georgia‘, ‘Hawaii‘,
  ‘Idaho‘, ‘Illinois‘, ‘Indiana‘, ‘Iowa‘, ‘Kansas‘, ‘Kentucky‘, ‘Louisiana‘,
  ‘Maine‘, ‘Maryland‘, ‘Massachusetts‘, ‘Michigan‘, ‘Minnesota‘,
  ‘Mississippi‘, ‘Missouri‘, ‘Montana‘, ‘Nebraska‘, ‘Nevada‘, ‘New Hampshire‘,
  ‘New Jersey‘, ‘New Mexico‘, ‘New York‘, ‘North Carolina‘, ‘North Dakota‘,
  ‘Ohio‘, ‘Oklahoma‘, ‘Oregon‘, ‘Pennsylvania‘, ‘Rhode Island‘,
  ‘South Carolina‘, ‘South Dakota‘, ‘Tennessee‘, ‘Texas‘, ‘Utah‘, ‘Vermont‘,
  ‘Virginia‘, ‘Washington‘, ‘West Virginia‘, ‘Wisconsin‘, ‘Wyoming‘
];

var custome_template_countries = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace(‘name‘),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  limit: 10,
  local: $.map(_data_states_template_countries, function(state) { return { name: state }; })
});

// kicks off the loading/processing of `local` and `prefetch`
custome_template_countries.initialize();

$(‘#custom-templates .typeahead‘).typeahead(null, {

  displayKey: ‘name‘,
  source: custome_template_countries.ttAdapter(),
  templates: {
    empty: [
      ‘<div class="empty-message">‘,
      ‘unable to find a country‘,
      ‘</div>‘
    ].join(‘\n‘),
    suggestion: Handlebars.compile(‘<p><strong>{{name}}</strong></p>‘)
  }
});
</script>

<p>5.multiple data set</p>

<style>
#multiple-datasets .league-name {
  margin: 0 20px 5px 20px;
  padding: 3px 0;
  border-bottom: 1px solid #ccc;
}
</style>

<div id="multiple-datasets">
  <input class="typeahead" type="text" placeholder="NBA and NHL teams">
</div>

<script>
var _data_nhlteam = [{ "team": "New Jersey Devils" },{ "team": "New York Islanders" },{ "team": "New York Rangers" },{ "team": "Philadelphia Flyers" },{ "team": "Pittsburgh Penguins" },{ "team": "Chicago Blackhawks" },{ "team": "Columbus Blue Jackets" },{ "team": "Detroit Red Wings" },{ "team": "Nashville Predators" },{ "team": "St. Louis Blues" },{ "team": "Boston Bruins" },{ "team": "Buffalo Sabres" },{ "team": "Montreal Canadiens" },{ "team": "Ottawa Senators" },{ "team": "Toronto Maple Leafs" },{ "team": "Calgary Flames" },{ "team": "Colorado Avalanche" },{ "team": "Edmonton Oilers" },{ "team": "Minnesota Wild" },{ "team": "Vancouver Canucks" },{ "team": "Carolina Hurricanes" },{ "team": "Florida Panthers" },{ "team": "Tampa Bay Lightning" },{ "team": "Washington Capitals" },{ "team": "Winnipeg Jets" },{ "team": "Anaheim Ducks" },{ "team": "Dallas Stars" },{ "team": "Los Angeles Kings" },{ "team": "Phoenix Coyotes" },{ "team": "San Jose Sharks" }];

var _data_nbateam = [{ "team": "Boston Celtics" },{ "team": "Dallas Mavericks" },{ "team": "Brooklyn Nets" },{ "team": "Houston Rockets" },{ "team": "New York Knicks" },{ "team": "Memphis Grizzlies" },{ "team": "Philadelphia 76ers" },{ "team": "New Orleans Hornets" },{ "team": "Toronto Raptors" },{ "team": "San Antonio Spurs" },{ "team": "Chicago Bulls" },{ "team": "Denver Nuggets" },{ "team": "Cleveland Cavaliers" },{ "team": "Minnesota Timberwolves" },{ "team": "Detroit Pistons" },{ "team": "Portland Trail Blazers" },{ "team": "Indiana Pacers" },{ "team": "Oklahoma City Thunder" },{ "team": "Milwaukee Bucks" },{ "team": "Utah Jazz" },{ "team": "Atlanta Hawks" },{ "team": "Golden State Warriors" },{ "team": "Charlotte Bobcats" },{ "team": "Los Angeles Clippers" },{ "team": "Miami Heat" },{ "team": "Los Angeles Lakers" },{ "team": "Orlando Magic" },{ "team": "Phoenix Suns" },{ "team": "Washington Wizards" },{ "team": "Sacramento Kings" }];

var nhlTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace(‘team‘),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: _data_nhlteam
});

var nbaTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace(‘team‘),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: _data_nbateam
});

nhlTeams.initialize();
nbaTeams.initialize();

$(‘#multiple-datasets .typeahead‘).typeahead({
  highlight: true
},
{
  displayKey: ‘team‘,
  source: nbaTeams.ttAdapter(),
  templates: {
  header: ‘<h3 class="league-name">NBA Teams</h3>‘
  }
},
{
  displayKey: ‘team‘,
  source: nhlTeams.ttAdapter(),
  templates: {
   header: ‘<h3 class="league-name">NHL Teams</h3>‘
  }
});

</script>

<p>
6. scrollable drop down
</p>

<style>
#scrollable-dropdown-menu .tt-dropdown-menu {
  max-height: 100px;
  width:600px;
  overflow-y: auto;
}
</style>

<div id="scrollable-dropdown-menu">
  <input class="typeahead" type="text" placeholder="Countries">
</div>

<script>
var _data_scrollable_dropdown_countries = [‘Alabama‘, ‘Alaska‘, ‘Arizona‘, ‘Arkansas‘, ‘California‘,
  ‘Colorado‘, ‘Connecticut‘, ‘Delaware‘, ‘Florida‘, ‘Georgia‘, ‘Hawaii‘,
  ‘Idaho‘, ‘Illinois‘, ‘Indiana‘, ‘Iowa‘, ‘Kansas‘, ‘Kentucky‘, ‘Louisiana‘,
  ‘Maine‘, ‘Maryland‘, ‘Massachusetts‘, ‘Michigan‘, ‘Minnesota‘,
  ‘Mississippi‘, ‘Missouri‘, ‘Montana‘, ‘Nebraska‘, ‘Nevada‘, ‘New Hampshire‘,
  ‘New Jersey‘, ‘New Mexico‘, ‘New York‘, ‘North Carolina‘, ‘North Dakota‘,
  ‘Ohio‘, ‘Oklahoma‘, ‘Oregon‘, ‘Pennsylvania‘, ‘Rhode Island‘,
  ‘South Carolina‘, ‘South Dakota‘, ‘Tennessee‘, ‘Texas‘, ‘Utah‘, ‘Vermont‘,
  ‘Virginia‘, ‘Washington‘, ‘West Virginia‘, ‘Wisconsin‘, ‘Wyoming‘
];

var _data_scrollable_dropdown_countries = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace(‘name‘),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  limit: 10,
  local: $.map(_data_states_template_countries, function(state) { return { name: state }; })
});

// kicks off the loading/processing of `local` and `prefetch`
_data_scrollable_dropdown_countries.initialize();

$(‘#scrollable-dropdown-menu .typeahead‘).typeahead(null, {
  name: ‘countries‘,
  displayKey: ‘name‘,
  source: _data_scrollable_dropdown_countries.ttAdapter()
});

</script>
时间: 2024-11-07 23:33:31

使用typeahead js 做quick search的相关文章

用js做登录的用户名判定

<script type="text/javascript" language="javascript" src="JS/jquery.js"></script>    <script language="javascript" type="text/javascript">      $(document).ready(function() {            

socket.io+angular.js+express.js做个聊天应用(三)

接着前面博客文章socket.io+angular.js+express.js做个聊天应用(二) 首先开发之前先介绍下bower.它是用来管理前端类库的(详细介绍,安装可看http://blog.csdn.net/edagarli/article/details/26359535) [email protected]:~/projects/nodejs/chattingnode$ bower Usage: bower <command> [<args>] [<options&

【微收藏】来自Twitter的自动文字补齐jQuery插件 - Typeahead.js

没图没逼格 事发有因 该插件可以结合本地数据进行一些操作.推荐关注一下H5的几种数据存储的方式(localstorage与sessionstorage.IndexedDB.离线缓存manifest文件).事关移动端优化,找时间再仔细详细总结一下,静候下一个时段. 主要特性 支持数据本地保存,客户端加载,优化加载速度 支持多语言,并且支持阿拉伯文 支持Hogan.js模板引擎整合 支持多数据集拼装 支持本地和远程的数据集 项目地址 http://twitter.github.io/typeahea

[3] 用D3.js做一个简单的图表吧!

本人的个人博客为: www.ourd3js.com csdn博客为: blog.csdn.net/lzhlzz 转载请注明出处,谢谢. 前面说了几节,都是对文字进行处理,这一节中将用 D3.js 做一个简单的柱形图. 做柱形图有很多种方法,比如用 HTML 的 div 标签,或用 svg . 推荐用 SVG 来做各种图形.SVG 意为可缩放矢量图形(Scalable Vector Graphics),SVG 使用 XML 格式定义图像,不清楚什么是SVG的朋友请先在 w3cschools 学习下

typeahead.js 使用记录

github地址:https://github.com/twitter/typeahead.js 在aceAdmin界面模板中,有typeahead这一控件,版本号为0.10.2 , 这个版本对 minLength:0这个参数无效,所以我就到github中找到新版本0.11.1 替换,在此记录使用过程中的一些注意事项 基本代码 var gameNameList = ['abc', 'abd', 'cde', 'xyz']; var gameNameMatcher = function(strs)

在ASP.NET MVC中使用typeahead.js支持预先输入,即智能提示

使用typeahead.js可以实现预先输入,即智能提示,本篇在ASP.NET MVC下实现.实现效果如下: 首先是有关城市的模型. public class City { public int Id { get; set; } public string Name { get; set; } public string PinYin { get; set; } } 在HomeController中响应前端请求返回有关City的json数据. public ActionResult GetCit

django Forgienkey字段 在前台用js做处理

在我做的项目中有个选择省城市的选项,这两个字段的关系是一对多的关系class Province(models.Model): # 省会      name = models.CharField(max_length=30) class City(models.Model): #城市      name = models.CharField(max_length=30)       province = models.ForeignKey(Province) 前台代码:<html><hea

java--css+js做的树形菜单(完整版)

jsp页面: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":"

JS中location.search什么意思

JS中location.search什么意思 设置或获取 网页地址跟在问号后面的部分 当以get方式在url中传递了请求参数时,可以利用location的search属性提取参数的值,下面的代码把参数的名称和对应的值存储在2个数组中. <script>function test(){var url=window.location.search;if(url.indexOf("?")!=-1) {    var str = url.substr(1)     strs = s