Perform action when clicking HTML5 datalist option

后端 未结 3 2124
梦毁少年i
梦毁少年i 2020-11-28 12:26

I\'m using a


And using AJAX to populate the list



        
3条回答
  •  时光说笑
    2020-11-28 12:33

    Sorry for digging up this question, but I've had a similar problem and have a solution, that should work for you, too.

    function onInput() {
        var val = document.getElementById("input").value;
        var opts = document.getElementById('dlist').childNodes;
        for (var i = 0; i < opts.length; i++) {
          if (opts[i].value === val) {
            // An item was selected from the list!
            // yourCallbackHere()
            alert(opts[i].value);
            break;
          }
        }
      }
    
    
    
      
      
    

    This solution is derived from Stephan Mullers solution. It should work with a dynamically populated datalist as well.

    Unfortunaltely there is no way to tell whether the user clicked on an item from the datalist or selected it by pressing the tab-key or typed the whole string by hand.

提交回复
热议问题