9

Sto provando a chiamare il mio URL remoto con l'ultima parte del valore di input. Mi piacerebbe fare qualcosa di simile:Bootstrap 3 typeahead.js - query per parte di typeahead val

$('#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 
}); 

e quando l'oggetto a discesa selezionato,

enter image description here

aggiungere nuovo valore alla fine della riga

enter image description here

Qualsiasi idea come farlo funzionare?

+0

Si consiglia di c Inoltre, è necessario prima ottenere tutti i valori separati da virgola nel proprio input e rimuoverli dal set di dati risultante. prima di utilizzare l'ultimo valore di input per mostrare l'elenco dei suggerimenti, a meno che non si preveda di consentire duplicati. Probabilmente dovrai disabilitare anche il completamento automatico/suggerimento? dal momento che immagino che influenzerà il tuo contributo. – Pricey

risposta

0

Per Bootstrap 3 è possibile utilizzare Bootstrap-3-Typeahead.

È necessario sovrascrivere le funzioni updater e matcher. Per la funzione matcher è possibile utilizzare il codice dal tuo funzione di sostituzione come segue:

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()); 
} 

utilizzare il seguente codice per la vostra update:

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

(ultima partita occorrenza da: JavaScript: replace last occurrence of text in a string)

Esempio completo:

$('.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

Partendo dal presupposto che "query con l'ultima parte" funziona per voi, è possibile utilizzare filter: function(response) {...} per popolare e restituire una serie di riferimenti che hanno adeguato value e title a fare quello che vuoi.

Problemi correlati