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

后端 未结 2 2024
孤城傲影
孤城傲影 2021-01-04 18:19

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: {
             


        
相关标签:
2条回答
  • 2021-01-04 18:54

    Assuming that "query with the last part" works for you, you can use filter: function(response) {...} to populate and return an array of datums that have appropriate value and title to do what you want.

    0 讨论(0)
  • 2021-01-04 19:18

    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());
        }
        }
    
    );
    
    0 讨论(0)
提交回复
热议问题