type suggestion examples bootstrap javascript twitter-bootstrap-3 typeahead.js

javascript - suggestion - typeahead states



Twitter Typeahead.js: muestra todas las opciones cuando hace clic/foco (8)

Estoy usando Typeahead.js en una entrada de texto de autocompletar, y es genial. Pero necesito activar el menú desplegable con todas las opciones disponibles cuando la entrada obtiene el foco. Cada solución posible que he visto implica inicializar la entrada con algún valor, pero necesito mostrar todas las opciones.

¿Cómo podría lograr esto?


Cualquier respuesta que diga "minLength: 0 es todo lo que necesita", NO ES VERDADERA.

"Out of the Box" Typeahead v0.11.1 "necesita" minLength establecido en 0, pero TAMBIÉN si está utilizando el motor Bloodhound de fábrica, entonces debe asegurarse de establecer

identify: function(obj) { return obj.team; },

en tu objeto Bloodhound ...

También necesita una función de "intermediario" para manejar su "consulta vacía", que es donde le indicará a Bloodhound que coopere.

function nflTeamsWithDefaults(q, sync) { if (q === '''') { sync(nflTeams.all()); // This is the only change needed to get ''ALL'' items as the defaults } else { nflTeams.search(q, sync); } }

Puedes ver el EJEMPLO COMPLETO aquí ...

var nflTeams = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace(''team''), queryTokenizer: Bloodhound.tokenizers.whitespace, identify: function(obj) { return obj.team; }, prefetch: ''../data/nfl.json'' }); function nflTeamsWithDefaults(q, sync) { if (q === '''') { sync(nflTeams.all()); // This is the only change needed to get ''ALL'' items as the defaults } else { nflTeams.search(q, sync); } } $(''#default-suggestions .typeahead'').typeahead({ minLength: 0, highlight: true }, { name: ''nfl-teams'', display: ''team'', source: nflTeamsWithDefaults });

MÁS ESPECÍFICAMENTE, PUEDE VER LA SUGERENCIA OFICIAL DE TWITTER TYPEAHEAD DEFAULT EN EL EJEMPLO DE ENFOQUE EN LA SIGUIENTE DIRECCIÓN, CON EL CAMBIO SENCILLO DE .get () TO .all () (VEA ARRIBA O ABAJO)

http://twitter.github.io/typeahead.js/examples/#default-suggestions

... espero que esto ayude a alguien, ya que me tomó algo de tiempo encontrar esta información (la encontré siguiendo todos los informes de errores y experimentando para encontrar el método .all ()) ...


En typeahead v.0.11.1, se ha aplicado el parche al que se hace referencia en otras respuestas. Puede lograr esto con la opción:

minLength: 0

Funciona con el teclado o el mouse. Sin cambios de código o nuevos eventos necesarios.


Hay una manera de hacer esto ahora sin tener que modificar el archivo fuente typeahead. Tienes que hacer dos cosas: establecer minlength en 0 y también agregar un controlador de eventos para el evento de enfoque: en el ejemplo de abajo que copié del primer ejemplo en la página de Twitter ( https://twitter.github.io/typeahead. js / examples / ) - asegúrese de que la ubicación para typeahead.js y jquery-ui.js es correcta.

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="typeahead.js"></script> <script src="jquery-ui.js"></script> <script> $(function(){ var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substrRegex; // 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)) { // the typeahead jQuery plugin expects suggestions to a // JavaScript object, refer to typeahead docs for more info matches.push({ value: str }); } }); cb(matches); }; }; var states = [''Alabama'', ''Alaska'', ''Arizona'', ''Arkansas'', ''California'', ''Colorado'', ''Connecticut'', ''Delaware'', ''Florida'', ''Georgia'', ''Hawaii'', ''Idaho'', ''Illinois'', ''Indiana'', ''Iowa'', ''Kansas'', ''Kentucky'', ''Louisiana'', ''Maine'', ''Maryland'', ''Massachusetts'', ''Michigan'', ''Minnesota'', ''Mississippi'', ''Missouri'', ''Montana'', ''Nebraska'', ''Nevada'', ''New Hampshire'', ''New Jersey'', ''New Mexico'', ''New York'', ''North Carolina'', ''North Dakota'', ''Ohio'', ''Oklahoma'', ''Oregon'', ''Pennsylvania'', ''Rhode Island'', ''South Carolina'', ''South Dakota'', ''Tennessee'', ''Texas'', ''Utah'', ''Vermont'', ''Virginia'', ''Washington'', ''West Virginia'', ''Wisconsin'', ''Wyoming'' ]; $(''.typeahead'').typeahead({ hint: true, highlight: true, minLength: 0 }, { name: ''states'', displayKey: ''value'', source: substringMatcher(states) }); $(''.typeahead'').on( ''focus'', function() { if($(this).val() === '''') // you can also check for minLength $(this).data().ttTypeahead.input.trigger(''queryChanged'', ''''); }); }); </script> </head> <body> <input class="typeahead" type="text" placeholder="States of USA"> </div> </body> </html>

Verificado esto funciona con 0.10.5. Nota: Se encontró que esto no funciona con el motor de búsqueda Bloodhound ya que queryTokenizer for Bloodhound espera un personaje.


Hay una manera más fácil de hacer esto ahora sin modificar la fuente. Puede ser que la fuente haya cambiado desde que esta fue originalmente respondida, pero pensé que valía la pena ponerla aquí por las dudas.

Después de crear el typeahead:

var $element = $(''#myTextElement''); $element.typeahead({ source: [''Billy'', ''Brenda'', ''Brian'', ''Bobby''] });

Simplemente configure minLength en 0:

$element.data(''typeahead'').options.minLength = 0;

Las opciones de minLength se fuerzan a 1 cuando se crea typeahead, pero puede establecerlo después de la creación y funciona perfectamente.


Hice una modificación rápida a 10.2 que hizo que el ejemplo de "los básicos" que se encuentra aquí se muestre en foco.

Cambié el mixin _onFocus (línea 1459) DE:

_onFocused: function onFocused() { this.isActivated = true; this.dropdown.open(); },

A:

_onFocused: function onFocused() { this.isActivated = true; var val = this.input.getInputValue(); var query = Input.normalizeQuery(val); this.dropdown.update(query); this.dropdown.open(); },

No es oficial, pero hizo el trabajo.



Otra opción es usar las API no públicas de Typeahead. El objeto Typeahead completo está disponible a través del método de data de jQuery.

var _typeaheadElem = $(''#myInput'').find(''.typeahead''); var _typeahead = _typeaheadElem.data(''ttTypeahead''); _typeaheadElem.focus(function() { /* WARNING: This is hackery abusing non-public Typeahead APIs */ if (_typeaheadElem.val() === "") { var input = _typeahead.input; //Reference to the TA Input class //Set the component''s current query to something !== input. input.query = "Recent People"; input._onInput(""); } });

Vea más código que funciona en v0.10.2 http://pastebin.com/adWHFupF

Esto está relacionado con PR 719 https://github.com/twitter/typeahead.js/pull/719


Usando 0.10.4

Para devolver todos los resultados de la consulta en blanco, agregue lo siguiente en la línea 450 de bloodhound.js

if (query == "") { return that.datums; }

Para desencadenar la coincidencia en el foco desencadenar el evento de tecla abajo en su entrada cuando se enfoca

$(input_element).on("click", function () { ev = $.Event("keydown") ev.keyCode = ev.which = 40 $(this).trigger(ev) return true });