52 Chapter 3—Intelligent Forms
For the option elements within the datalist, you just need to fill the value at-
tribute. Further attributes and a text node are possible but not required for this
use. If the user clicks the Submit button, the content of the text field is prefixed
with the character string http:// and the browser is redirected to the resulting
URL (window.location):
Listing 3.1 The “datalist” element filled with Internet addresses
<form>
<p>
<label for=url>Goto</label>
http://<input type=text id=url name=homepage
list=hompages autofocus>
<datalist id=hompages>
<option value=www.google.com>
<option value=html5.komplett.cc/welcome>
<option value=slashdot.org>
<option value=wired.com>
</datalist>
<input type=submit
onclick="window.location =
'http://'+document.getElementById('url').value;
return false;" >
</form>
If you want to equip older browsers with a selection list without duplicating the
HTML code, you can fall back on the following trick. Because browsers support-
ing the datalist element ignore an enclosed select element, they display the
new HTML5 select element. Older browsers, however, display a selection list for
the text field with predefined links, which will be inserted into the text field when
the selection is changed.
As you can see in Listing 3.2, we need to add a text node to the option elements
because the “old” select element does not show the content of the value attri-
bute but instead shows the text:
Listing 3.2 A “datalist” with the fallback for older browsers
<datalist id=hompages>
<select name=homepage
onchange="document.getElementById('url').value =
document.forms[0].homepage[1].value" >
<option value=www.google.com>www.google.com
<option
value=html5.komplett.cc/welcome>html5.komplett.cc/welcome
<option value=slashdot.org>slashdot.org
<option value=wired.com>wired.com
</select>
</datalist>