如何在输入数据列表中设置默认值并仍然有下拉列表? [英] How to set default value in input datalist and still have the drop down?

查看:39
本文介绍了如何在输入数据列表中设置默认值并仍然有下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 datalist HTML 属性来获取下拉输入框:

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?

推荐答案

我不知道本机无法做到这一点.当输入字段具有值时,您可以制作一个助手"div 以使用.我无法隐藏本机下拉菜单,所以我重命名了 ID.使用 jQuery.

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>

脚本

$(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

这篇关于如何在输入数据列表中设置默认值并仍然有下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆