简体   繁体   中英

Using Bootstrap 3 and Twitter typeahead.js for autocomplete

I've tried with no success so far to get auto-complete working with Bootstrap 3 and twitter typeahead.js. Specifically, I'm trying to allow searching a MySQL database of students. When a user selects the student from the auto suggest results, I also need other data aside from the name, in this case their ID. Here is some example JSON that is returned:

[{"firstname":"Tyler","lastname":"Smith","id":"33"},
 {"firstname":"Tyler","lastname":"Wilson","id":"190"},
 {"firstname":"Tyler","lastname":"Doe","id":"347"},
 {"firstname":"Tyler","lastname":"Carson","id":"377"}]

I found this code, which works with a flat array of only names, so the above will not work:

    $('#studentFName').typeahead({
        name: 'FNameSearch',
        remote: 'students?query=%QUERY',
            updater: function(item) {
            return item;
        }
    })

However I need more then just the first name, I need to be able to get the data along with the name and append it to a result div. I've done this in jquery UI, I just cant get it to work with typeahead.js.

Help is very much appreciated.

If you are using the latest version of Twitter Typeahead.js ( 0.10.2 ) here is an updated approach that might work for you ( new demo ).

With this HTML

<table>
  <tr>
    <td rowspan="3"><input name='students' type="text" placeholder="Students" /></td>
    <td>First Name:</td>
    <td><input name='FName' type="text" readonly="readonly" /></td>
  </tr>
  <tr>
      <td>Last Name:</td>
      <td><input name='LName' type="text" readonly="readonly" /></td>
  </tr>
  <tr>
      <td>ID:</td>
      <td><input name='ID' type="text" readonly="readonly" /></td>
  </tr>
</table>

And this JavaScript (I'm using the local approach to avoid setting up a mock AJAX service though this will work with the remote data source approach as well)

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;
    // 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['value'])) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push(str);
      }
    });
    cb(matches);
  };
};
var students = [{
        "value": "Tyler Smith",
        "firstname": "Tyler",
        "lastname": "Smith",
        "id": "33"
    }, {
        "value": "Tyler Wilson",
        "firstname": "Tyler",
        "lastname": "Wilson",
        "id": "190"
    }, {
        "value": "Tyler Doe",
        "firstname": "Tyler",
        "lastname": "Doe",
        "id": "347"
    }, {
        "value": "Tyler Carson",
        "firstname": "Tyler",
        "lastname": "Carson",
        "id": "377"
    }];

$('input[name=students]').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},{
  name: 'Students',
  displayKey: 'value',
  source: substringMatcher(students)
}).on('typeahead:selected', function (object, datum) {
    // Example: {type: "typeahead:selected", timeStamp: 1377890016108, jQuery203017338529066182673: true, isTrigger: 3, namespace: ""...}
    //console.log(object);

    // Datum containg value, tokens, and custom properties
    $('input[name=FName]').val(datum.firstname);
    $('input[name=LName]').val(datum.lastname);
    $('input[name=ID]').val(datum.id);
});

If you are using Twitter's Typeahead.js pre 0.10.2 then here is an approach that might work for you ( old demo this points to a missing copy of typeahead.js, but I kept this in case it is still helpful):

Using the same HTML

And this JavaScript (I'm using the local approach to avoid setting up a mock AJAX service though this will work with the remote data source approach as well)

$('input[name=students]').typeahead({
    name: 'Students',
    local: [{
        "value": "Tyler Smith",
        "firstname": "Tyler",
        "lastname": "Smith",
        "id": "33"
    }, {
        "value": "Tyler Wilson",
        "firstname": "Tyler",
        "lastname": "Wilson",
        "id": "190"
    }, {
        "value": "Tyler Doe",
        "firstname": "Tyler",
        "lastname": "Doe",
        "id": "347"
    }, {
        "value": "Tyler Carson",
        "firstname": "Tyler",
        "lastname": "Carson",
        "id": "377"
    }] 
}).on('typeahead:selected', function (object, datum) {
    // Example: {type: "typeahead:selected", timeStamp: 1377890016108, jQuery203017338529066182673: true, isTrigger: 3, namespace: ""...}
    //console.log(object);

    // Datum containg value, tokens, and custom properties
    $('input[name=FName]').val(datum.firstname);
    $('input[name=LName]').val(datum.lastname);
    $('input[name=ID]').val(datum.id);
});

The only change you need to make to your data is to add a value attribute that represents what will be visually displayed in the auto-complete box. As you can see you are free to keep all of your individual data elements (with the same names even), to highlight a way to use them I've added an extra "details form" that updates on select.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM