Skip to content

Instantly share code, notes, and snippets.

@kedar2a
Last active October 22, 2016 15:17
Show Gist options
  • Save kedar2a/87525a430054125350844c51f1c4df7b to your computer and use it in GitHub Desktop.
Save kedar2a/87525a430054125350844c51f1c4df7b to your computer and use it in GitHub Desktop.
Dropdown with HTML5 Datalist, enables built-in search and showing options in dropdown
<!DOCTYPE html>
<html>
<head>
<title>Dropdown with HTML5 Datalist</title>
<style type="text/css">
datalist{
display: none;
}
select{
width: 100%;
}
#container{
width: 190px;
}
</style>
</head>
<body>
<!-- Keep eyeon further specs and updates by W3C -->
<!-- https://www.w3.org/TR/html5/forms.html#the-datalist-element -->
<div id="container">
<input type="text" list="text-editors">
<button>▼</button>
<datalist id="text-editors">
<select multiple size="5">
<option value="Apple">Apple
<option value="Cherry">Cherry
<option value="Gauva">Gauva
<option value="Mango">Mango
<option value="Pinapple">Pinapple
<option value="Stawberry">Stawberry
<option value="Grape">Grape
</select>
</datalist>
</div>
<script type="text/javascript">
button = document.querySelector('button');
datalist = document.querySelector('datalist');
select = document.querySelector('select');
options = select.options;
button.addEventListener('click', toggle_ddl);
function toggle_ddl(){
/* if DDL is hidden */
if(datalist.style.display === ''){
/* show DDL */
datalist.style.display = 'block';
this.textContent="▲";
var val = input.value;
for(var i=0; i<options.length; i++) {
if ( options[i].text === val ) {
select.selectedIndex = i; break;
}
}
}
else hide_select();
}
function hide_select(){
/* hide DDL */
datalist.style.display = '';
button.textContent="▼";
}
/* when the user wants to type into text field, hide DDL */
input = document.querySelector('input');
input.addEventListener('focus', hide_select);
/* when user selects an option from DDL, write it to text field */
select.addEventListener('change',fill_input);
function fill_input(){
input.value = options[this.selectedIndex].value;
hide_select();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment