zoukankan      html  css  js  c++  java
  • Bootstrap 3 Typeahead

    本文转自: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

  • 相关阅读:
    数据库备份脚本
    redismyadmin安装(支持redis4 集群模式)
    elasticsearch ik安装
    centos7.2 +cloudstack 4.11 +KVM +ceph 安装配置(网卡带聚合)
    cloudstack4.11+KVM+4网卡bond5+briage 交换机不作配置
    web service:AxisFault faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    根据WSDL生成客户端代码(XFire)
    Apache axis2 + Eclipse 开发 WebService
    The processing instruction target matching "[xX][mM][lL]" is not allowed.
    使用dom4j解析xml文件,并封装为javabean对象
  • 原文地址:https://www.cnblogs.com/freeliver54/p/7238650.html
Copyright © 2011-2022 走看看