Skip to content
Advertisement

How to set default value in input datalist and still have the drop down?

I am using the datalist HTML property to get a drop down inout box:

<input list="orderTypes" value="Book">
<datalist id="orderTypes">
  <option value="Book">
  <option value="Copy">
  <option value="Page">
</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

<input list="orderTypes" id="dlInput">
<div id="helper" style="display:none;position:absolute;z-index:200;border:1pt solid #ccc;"></div>
<datalist id="orderTypes" style="z-index:100;">
   <option value="Book">
   <option value="Copy">    
   <option value="Page">
</datalist>

script

$(function(){
    // make a copy of datalist 
    var dl="";
    $("#orderTypes option").each(function(){
            dl+="<div class='dlOption'>"+$(this).val()+"</div>";
    });
    $("#helper").html(dl);
    $("#helper").width( $("#dlInput").width() );

    $(document).on("click","#dlInput",function(){
        // display list if it has value
        var lv=$("#dlInput").val();
        if( lv.length ){
                $("#orderTypes").attr("id","orderTypesHide");
                $("#helper").show();
        }
    });

    $(document).on("click",".dlOption",function(){
        $("#dlInput").val( $(this).html() );
        $("#helper").hide();
    });

    $(document).on("change","#dlInput",function(){
        if( $(this).val()==="" ){
            $("#orderTypesHide").attr("id","orderTypes");
            $("#helper").hide();
        }
    }); 
}); 

jsFiddle

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement