Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 3 typeahead.js - query by part of typeahead val

I'm trying to call my remote url with last part of input value. I would like to do something like this:

    $('#typeahead').typeahead({
    remote: {
        url: '/ajax/tags/get/?name=%QUERY',
        replace: function (url, query) {
            var last = query.split(',');
            last = $.trim(last[last.length-1]);
            return url.replace('%QUERY', last);
        }
    },
    limit : 10
});

and when dropdown item selected,

enter image description here

add new value to end of line

enter image description here

Any idea how to make that work?

like image 805
Daniil Mashkin Avatar asked Aug 19 '13 21:08

Daniil Mashkin


Video Answer


1 Answers

For Bootstrap 3 you can use Bootstrap-3-Typeahead.

You will have to overwrite the updater and matcher functions. For the matcher function you can use the code from your replace function as follows:

matcher: function (item) {
        var last = this.query.split(',');
        this.query = $.trim(last[last.length-1]);

        if(this.query.length) return ~item.toLowerCase().indexOf(this.query.toLowerCase());
}

Use the following code for your update:

updater: function (item) {
      return this.$element.val().replace(new RegExp(this.query + '$'),'') + item + ',';
    }

(match last occurrence from: JavaScript: replace last occurrence of text in a string )

Complete example:

$('.typeahead').typeahead (
{
items: 4,
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);

}

  , updater: function (item) {
      return this.$element.val().replace(new RegExp(this.query + '$'),'') + item + ',';
    }
    , matcher: function (item) {
        var last = this.query.split(',');
        this.query = $.trim(last[last.length-1]);

        if(this.query.length) return ~item.toLowerCase().indexOf(this.query.toLowerCase());
    }
    }

);
like image 163
Bass Jobsen Avatar answered Sep 29 '22 23:09

Bass Jobsen