I am using the datalist
HTML property to get a drop down inout box:
JavaScript
x
6
1
<input list="orderTypes" value="Book">
2
<datalist id="orderTypes">
3
<option value="Book">
4
<option value="Copy">
5
<option value="Page">
6
</datalist>
The problem is that now I have to clear the input box to view all the drop down values. Is there a way to have a default value but still view all the values in the datalist when the drop down icon is clicked?
Advertisement
Answer
I know of no way to do this natively. You could make a “helper” div to use when the input field has value. I couldn’t hide the native drop down so I renamed the ID. Uses jQuery.
html
JavaScript
1
8
1
<input list="orderTypes" id="dlInput">
2
<div id="helper" style="display:none;position:absolute;z-index:200;border:1pt solid #ccc;"></div>
3
<datalist id="orderTypes" style="z-index:100;">
4
<option value="Book">
5
<option value="Copy">
6
<option value="Page">
7
</datalist>
8
script
JavaScript
1
31
31
1
$(function(){
2
// make a copy of datalist
3
var dl="";
4
$("#orderTypes option").each(function(){
5
dl+="<div class='dlOption'>"+$(this).val()+"</div>";
6
});
7
$("#helper").html(dl);
8
$("#helper").width( $("#dlInput").width() );
9
10
$(document).on("click","#dlInput",function(){
11
// display list if it has value
12
var lv=$("#dlInput").val();
13
if( lv.length ){
14
$("#orderTypes").attr("id","orderTypesHide");
15
$("#helper").show();
16
}
17
});
18
19
$(document).on("click",".dlOption",function(){
20
$("#dlInput").val( $(this).html() );
21
$("#helper").hide();
22
});
23
24
$(document).on("change","#dlInput",function(){
25
if( $(this).val()==="" ){
26
$("#orderTypesHide").attr("id","orderTypes");
27
$("#helper").hide();
28
}
29
});
30
});
31