Autocomplete nativo con datalist

17/Mar/2015 278

Un intersante y poco conocido elemento HTML5 es <datalist>, con el cual permite crear de forma nativa un campo de input con autocomplete, y con nativo me refiero sin JavaScript.

datalist

Para utilizarlo, necesitarás un campo de <input /> común y corriente y linkearlo con el listado de palabras/términos a ser desplegados cuando el usuario tipea en este <input />:

<label>Marcas de Cerveza</label>
<input list="cervezas" placeholder="Escribe una marca de cerveza:" />

Ahora construímos el listado con <datalist> y en cada <option> las opciones disponibles:

<datalist id="cervezas">
	<option value="Heineken" />
	<option value="Budweiser" />
	<option value="Skol" />
	<option value="Cristal" />
	<option value="Quilmes" />
	<option value="Estrella Damm" />
	<option value="Sol" />
	<option value="Cusqueña" />
	<option value="Paceña" />
	<option value="Tecate" />
	<option value="Corona" />
	<option value="Águila" />
	<option value="Guinness" />
	<option value="Carlsberg" />
	<option value="Becks" />
	<option value="Brahma" />
	<option value="Polar" />
	<option value="Medalla" />
</datalist>

Ver Ejemplo 1

Nótese que para linkear el <input /> con el <datalist> se utiliza el atributo list=»ID-DEL-DATALIST». Otro detalle, el autocomplete detecta las primeras letras de la palabra/término definido en cada <option /> y no las letras intermedias que contiene la palabra.

Carga dinámica de datos

Si la lista llega a ser muy extensa, podemos hacer una carga dinámica de las palabras/términos mediante AJAX. Para ello necesitaremos un poco de JavaScript.

Carguemos el listado de países en un campo mientras el usuario está escribiendo en él:

<input id="paises" list="json-paises" placeholder="Escribe el nombre de un país" />
<datalist id="json-paises"></datalist>

JavaScript para llamar el JSON por AJAX y llenar el <datalist> con los países:

// Definición de un par de variables
var dataList = document.querySelector('#json-paises'),
		input = document.querySelector('#paises');
// Creamos un nuevo XMLHttpRequest
var request = new XMLHttpRequest();
// Una ves listo, definimos eventos para sus estados
request.onreadystatechange = function(response) {
  if (request.readyState === 4) {
    if (request.status === 200) {
      // Parseando JSON
      var jsonOptions = JSON.parse(request.responseText);
      // Iterando sobre el arreglo JSON
      jsonOptions.forEach(function(item) {
        // Creando un option por cada país.
        var option = document.createElement('option');
        option.value = item;
        dataList.appendChild(option);
      });
      input.placeholder = "Escribe el nombre de un país";
    } else {
      // Error!
      input.placeholder = "Error al cargar lista de países ;^(";
    }
  }
};
// Cambiamos el texto del placeholder
input.placeholder = "Cargando países";
// Abrimos y enviamos el request
request.open('GET', 'json-paises.json', true);
request.send();

El formato del json-paises.json:

[
	"Afganistán", 
	"Albania", 
	"Alemania", 
	"Andorra", 
	"Angola", 
	"Anguila", 
	"Antigua y Barbuda",
	...
]

Ver Ejemplo 2

Soporte:

Desde IE10, pasando por Firefox, Chrome, Opera, Android Browser y sólo Safari decepcionando.

Links:

Comentarios

  1. ivermectin pills for humans [#]

    stromectol 3mg scabies https://stromectolforte.com/ ivermektin köp online where to buy ivermectin

  2. ivermectin sale [#]

    stromectol for sale online

    single endothelins aid

  3. stromectolforte.com [#]

    can you buy ivermectin in the us http://stromectolforte.com/ is ivermectin safe for people ivermektiini 1% kerma geneerinen

  4. modafinilhalflife [#]

    modafinil weight loss modalert online

  5. benadryl [#]

    citizen – http://allergyd.com

  6. buymodafinil [#]

    provigil over the counter where to buy modafinil

  7. bactrim ds dosage [#]

    bactrim ds side effects dosage https://bactrimhoprim.com/

  8. ivermectin walmart [#]

    ivermectin for humans lice

    elite dermal papilla actual

  9. cialis coupon [#]

    https://cialiswithdapoxetine.com/ cialis online

  10. www.pharmaceptica.com [#]

    chloroquine tab https://pharmaceptica.com/

  11. off white x nike [#]

    I actually wanted to write a small message in order to thank you for the unique items you are showing on this website. My considerable internet research has at the end of the day been recognized with reliable points to go over with my contacts. I ‘d admit that most of us website visitors actually are undeniably endowed to exist in a fine place with many awesome individuals with useful ideas. I feel really blessed to have encountered the website page and look forward to many more pleasurable times reading here. Thanks once more for all the details.

  12. curry 8 [#]

    I wish to show some thanks to the writer just for bailing me out of this type of setting. After browsing through the internet and getting thoughts that were not helpful, I assumed my life was done. Being alive without the solutions to the issues you’ve fixed by means of your good blog post is a crucial case, as well as the ones which could have negatively damaged my entire career if I had not discovered the website. Your know-how and kindness in taking care of all the details was very helpful. I don’t know what I would have done if I had not encountered such a thing like this. I can also at this time look ahead to my future. Thanks a lot very much for your professional and effective help. I won’t hesitate to endorse the blog to anybody who requires guide on this issue.

  13. bape clothing [#]

    My spouse and i ended up being really relieved that Edward managed to finish up his basic research while using the ideas he made through your web site. It is now and again perplexing to just be handing out tips and hints which most people could have been selling. Therefore we see we have the website owner to give thanks to because of that. The type of illustrations you made, the easy site menu, the relationships you help to engender – it’s got mostly astounding, and it’s really making our son and the family believe that this concept is brilliant, which is seriously vital. Thanks for the whole lot!

  14. steph curry shoes [#]

    I in addition to my friends came reading through the good ideas located on your web site and so instantly came up with a horrible feeling I never expressed respect to the site owner for those secrets. All of the men are actually consequently stimulated to read through all of them and have unquestionably been using these things. Appreciate your really being very thoughtful as well as for making a decision on this kind of really good tips most people are really eager to be informed on. Our own honest apologies for not expressing gratitude to you earlier.

  15. cheap jordans [#]

    I have to express thanks to you just for rescuing me from this particular circumstance. Right after checking throughout the internet and seeing concepts that were not helpful, I was thinking my entire life was over. Being alive without the answers to the issues you have solved by means of your short article is a serious case, and the ones which may have in a negative way affected my entire career if I had not come across your website. Your own personal training and kindness in playing with all things was valuable. I’m not sure what I would have done if I hadn’t come upon such a point like this. I’m able to now look forward to my future. Thanks a lot very much for your expert and effective help. I won’t hesitate to refer your blog to anyone who wants and needs support about this topic.

  16. stephen curry shoes [#]

    Needed to write you the bit of observation to help say thanks a lot once again for your stunning tactics you have shared in this article. This has been remarkably generous with people like you to supply freely all that some people could have offered for an electronic book in order to make some cash on their own, and in particular given that you could possibly have tried it if you decided. These tips likewise worked to become a fantastic way to realize that other individuals have the same dream similar to my very own to grasp a great deal more regarding this condition. I’m certain there are thousands of more pleasurable times ahead for folks who start reading your site.

  17. kyrie irving [#]

    I am only writing to let you know of the amazing experience my wife’s girl gained going through your web page. She noticed several details, most notably how it is like to have a marvelous coaching character to make folks quite simply have an understanding of selected problematic matters. You actually surpassed her desires. Many thanks for providing these powerful, dependable, revealing as well as cool guidance on your topic to Julie.

  18. lebron james shoes [#]

    My spouse and i felt so comfortable Jordan managed to complete his studies from the ideas he obtained out of your web page. It is now and again perplexing just to find yourself freely giving secrets that many some other people could have been selling. And we all consider we have the blog owner to be grateful to for that. The entire explanations you have made, the straightforward blog navigation, the friendships your site help foster – it’s most sensational, and it is aiding our son and our family imagine that the situation is fun, which is pretty vital. Many thanks for all!

  19. alex lyubinsky scammer [#]

    central park apartments rentberry scam ico 30m$ raised national city apartments

  20. modafinildrugtest [#]

    modafinil over the counter https://getmodafinilnow.com/

  21. bactrim dosage [#]

    sulfamethoxazole uses sulfamethoxazole trimethoprim

  22. prednisonesteroid [#]

    steroid prednisone what is prednisone prescribed for

  23. stromectol usa [#]

    stromectol generic http://stromectolforte.com/ acheter stromectol liquide stromectol

  24. drineepkle [#]

    prednisone drops after cataract surgery prednisone for gout

  25. bactrim ds side effects [#]

    bactrim side effects https://bactrimsulfamethoxazole.com/

  26. stromectolforte.com [#]

    stromectol online canada http://stromectolforte.com/ buy ivermectin online do i need a prescription for ivermectin

  27. provigilgeneric [#]

    modafinil uses modafinil mechanism of action

  28. GustavoVet [#]

    college essay writer
    rate my essay

CSSLab