The HTML5 Datalist Element: A New Method For Autocomplete
Join the DZone community and get the full member experience.
Join For FreeMost people use the jQuery library jQuery UI in their applications, this gives you access to a number of useful elements that you can use, these consist of the colour picker, sliders, accordions, dialog boxes, menus and progress bars. One of the most useful elements that is in the jQuery UI library is the autocomplete element.
This works by first creating a Javascript object which you can populate with a number of options which will be searched when you enter text in the autocomplete textbox.01.
<
script
>
02.
$(function() {
03.
var availableTags = [
04.
"ActionScript",
05.
"AppleScript",
06.
"Asp",
07.
"BASIC",
08.
"C",
09.
"C++",
10.
"Clojure",
11.
"COBOL",
12.
"ColdFusion",
13.
"Erlang",
14.
"Fortran",
15.
"Groovy",
16.
"Haskell",
17.
"Java",
18.
"JavaScript",
19.
"Lisp",
20.
"Perl",
21.
"PHP",
22.
"Python",
23.
"Ruby",
24.
"Scala",
25.
"Scheme"
26.
];
27.
$( "#tags" ).autocomplete({
28.
source: availableTags
29.
});
30.
});
31.
</
script
>
32.
33.
<
div
class
=
"ui-widget"
>
34.
<
label
for
=
"tags"
>Tags: </
label
>
35.
<
input
id
=
"tags"
/>
36.
</
div
>
There are lots of new features that come with HTML5 most of them use additional Javascript APIs, others replace existing functionality that we would use Javascript for such as form validation can now be replaced with the require attribute. The placeholder attribute is another feature that you used to have to use Javascript for.
There is an element in HTML5 called Datalist that will allow you to create an autocomplete boxes without using any Javascript.
First you create the datalist element which has an ID and a option list.
01.
<
datalist
id
=
"availableTags"
>
02.
<
option
value
=
"ActionScript"
>
03.
<
option
value
=
"AppleScript"
>
04.
<
option
value
=
"Asp"
>
05.
<
option
value
=
"BASIC"
>
06.
<
option
value
=
"C"
>
07.
<
option
value
=
"C++"
>
08.
<
option
value
=
"Clojure"
>
09.
<
option
value
=
"COBOL"
>
10.
<
option
value
=
"ColdFusion"
>
11.
<
option
value
=
"Erlang"
>
12.
<
option
value
=
"Fortran"
>
13.
<
option
value
=
"Groovy"
>
14.
<
option
value
=
"Haskell"
>
15.
<
option
value
=
"Java"
>
16.
<
option
value
=
"JavaScript"
>
17.
<
option
value
=
"Lisp"
>
18.
<
option
value
=
"Perl"
>
19.
<
option
value
=
"PHP"
>
20.
<
option
value
=
"Python"
>
21.
<
option
value
=
"Ruby"
>
22.
<
option
value
=
"Scala"
>
23.
<
option
value
=
"Scheme"
>
24.
</
datalist
>
Now we can create a input type of list to use these options in the autocomplete.
1.
<
input
name
=
"availableTags"
list
=
"availableTags"
/>
Browser Support
The datalist element is current supported in Chrome, Firefox and Opera.
View the current supported table to see exactly what browsers support it.
Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments