Quick Tip – Autocomplete Using HTML5 Datalist Element
Join the DZone community and get the full member experience.
Join For Freeusing datalist element
the use of a datalist element is straight forward. you create the datalist inside a phrasing element and write the autocomplete options inside of it:
<datalist id="dlcities"> <option value="seattle" /> <option value="las vegas" /> <option value="new york" /> <option value="salt lake city" /> </datalist>
in order to connect the previous list to a textbox and create the autocomplete functionality, you will use the new list attribute and give it the datalist id:
<input type="text" id="txt" name="txt" list="dlcities" />
the result of running the page will be:
creating on the fly datalist
one of the requirements i had in a project i did lately was to create a datalist on the fly. this can be achieved using basic javascript functionality. here the code sample:
(function () { var optionlist = ["seattle", "las vegas", "new york", "salt lake city"]; function filldatalist() { var container = document.getelementbyid('container'), i = 0, len = optionlist.length, dl = document.createelement('datalist'); dl.id = 'dlcities'; for (; i < len; i += 1) { var option = document.createelement('option'); option.value = optionlist[i]; dl.appendchild(option); } container.appendchild(dl); } window.addeventlistener("domcontentloaded", filldatalist, false); } ());
as you can see you have a predefined array with the same cities options from the previous code sample. the filldatalist function is called when the dom content loaded event is fired. in the filldatalist , all you have to do is to get the container element (that must be a phrasing element ) and append to it the created datalist . this example can be changed easily to use data retrieved from the server-side.
datalist browser support
as in all new html5 elements, currently the datalist isn’t supported in all of the browsers. the datalist is supported in chrome from version 20, in firefox from version 4, in internet explorer from version 10 and in opera from version 9. you can go to the following web page to see where the datalist is supported in more details.
summary
the datalist element can be useful when you have predefined options that you want to use as autocomplete in html controls. it’s lack of browsers support forces us to have fallbacks to the behavior using javascript control libraries such as the autocomplete control in jquery ui.
Opinions expressed by DZone contributors are their own.
Trending
-
Develop Hands-Free Weather Alerts To Ensure Safe Backpacking
-
CDNs: Speed Up Performance by Reducing Latency
-
Low Code vs. Traditional Development: A Comprehensive Comparison
-
What ChatGPT Needs Is Context
Comments