简体   繁体   English

如何将输入映射到我的数据列表选项?

[英]How to map input to my datalist option?

My code is the following: 我的代码如下:

HTML: HTML:

<input list="itemList" id="inputItemList"  type="text" class="form-control">
<datalist id="itemList" >
    <option value="Example" data-id="1">
</datalist>

Javascript: Javascript:

var element = $("#inputItemList");
var itemName = element.val();
var id = element.attr('data-id');

Through Javascript, I add <option> s to my datalist, where every option has custom data in the sort of data-id . 通过Javascript,我将<option>添加到我的数据列表中,其中每个选项都以data-id的形式包含自定义数据。 I may be doing it wrong, but when I query for the value in my <input> , I just have the value of the option; 我可能做错了,但是当我在<input>查询值时,我只有选项的值。 I am not able to get the other attributes from my <option> . 我无法从<option>获取其他属性。 Is there a way around this? 有没有解决的办法?

I also tried to get the selected option in <datalist> but when I did it, there is nothing selected in it. 我也尝试在<datalist>获取选定的选项,但是当我这样做时,没有任何选择。

Ok, here's the solution. 好的,这是解决方案。 You just have to listen to the input and then check against all the options: 您只需要侦听输入,然后对照所有选项进行检查:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>

<input list="itemList" id="inputItemList" type="text" class="form-control">

<datalist id="itemList" >
    <option value="Example 1" data-id="1">
    <option value="Example 2" data-id="2">
    <option value="Example 3" data-id="3">
    <option value="Example 4" data-id="4">
</datalist>

<script type="text/javascript">
    $(document).on('change',$('#inputItemList'),function(e){
        var theID = checkOption($(e.target).val());
        if(theID) {
            return console.log('Found match: ' + theID);
        } else {
            return console.log('No Match Found!');
        }
    })
    function checkOption(val) {
        var theID;
        $('#itemList option').each(function(){
            if(val.toLowerCase() == $(this).val().toLowerCase()){
                theID = $(this).data('id');
            }
        })
        return theID;
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM