简体   繁体   中英

How to map input to my datalist option?

My code is the following:

HTML:

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

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 . I may be doing it wrong, but when I query for the value in my <input> , I just have the value of the option; I am not able to get the other attributes from my <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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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