Pequeño complemento de Autocompletar para campos de entrada-AutoComplete. js

Tiempo de ejecución: 30 minutos. Empezar

Autor: kraaden
Views Total: 2,061
Sitio oficial: Ir a la web
Actualizado: November 23, 2018
Licencia: MIT

Vista prévia

Pequeño complemento de Autocompletar para campos de entrada-AutoComplete. js

Descripción

A very small autocomplete JavaScript library that allows the users to quickly select an option item from a group-enabled suggestion dropdown list.

Install it via NPM:

$ npm install autocompleter

Funcionamiento

Importe el autocompleter en el proyecto.

import autocomplete from 'autocompleter';
// or
var autocomplete = require('autocompleter');

O incluir directamente el archivo JavaScript en la página web:

<script src="autocomplete.js"></script>

No olvide incluir la hoja de estilo requerida que proporcionará los estilos CSS primarios para la lista de autocompletar.

<link rel="stylesheet" href="autocomplete.css">

Definir una matriz de sugerencias en el JavaScript que será capturado por el plugin a través de solicitudes AJAX.

var languages = [


{ label: 'JavaScript', item: 'JS' },


{ label: 'CSS 2 and 3', item: 'CSS' }


...
];

Inicialice el complemento en un campo de entrada y Capture los datos que definió en el paso anterior. Tenga en cuenta que también puede usar solicitudes AJAX en lugar de datos precargados

autocomplete({

input: document.getElementById("yourInput"),

fetch: function(text, update) {


text = text.toLowerCase();


var suggestions = languages.filter(n => n.label.toLowerCase().startsWith(text))


update(suggestions);

}
});

Si desea categorizar sus sugerencias en diferentes grupos.

var languages = [


{ label: 'JavaScript', item: 'JS', group: 'group-1' },


{ label: 'CSS 2 and 3', item: 'CSS', group: 'group-2' }


...
];

Más opciones de configuración:

autocomplete({


input: document.getElementById("yourInput"),

fetch: function(text, update) {


text = text.toLowerCase();


var suggestions = languages.filter(n => n.label.toLowerCase().startsWith(text))


update(suggestions);

},


// The minimum length, when autocomplete should appear on the screen

minLength: 2,


// The message that will be showed when there are no suggestions that match the entered value.

emptyMsg: '',


// The autocomplete container will have this class name if specified.

className: '',


// Called when user choose an item in autocomplete. The selected item will be passed as first parameter.

onSelect: null,


// This method allows you to override the rendering function.

 // It will be called for each suggestion and the suggestion object will be passed as first parameter.

 // This function must return a DIV element or undefined to skip rendering.

render: null,


 // The same as render, but will be called for each group.

 // The first parameter of the function will be the group name.

 // This function must return a DIV element or undefined to skip rendering.

renderGroup: null

});

Registro de cambios

11/23/2018

  • Asegúrese de que maxHeight siempre es positivo

11/22/2018

  • rendimiento de inicialización mejorado/error de desplazamiento fijo
  • pasar ' false ' a la función fetch
  • pos fijos

11/02/2018

  • problema de exportación predeterminado fijo

10/26/2018

  • pequeña refactorización

10/23/2018

  • usar la variable de doc local en lugar del documento

10/11/2018

  • corregido el cálculo de la posición equivocada

10/10/2018

  • usar documentFragment para acelerar el autocompletador cuando se usan listas grandes

08/07/2018

  • etiqueta es opcional ahora, porque no es necesario para la representación personalizada

08/06/2018

  • añadido nuevos parámetros para pasar el valor actual a las funciones de representación

08/03/2018

  • mejoras & controlador de eventos agregado para desplazarse

Te puede interesar: