Perform action when clicking HTML5 datalist option

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

I\'m using a


And using AJAX to populate the list



        
3条回答
  •  孤街浪徒
    2020-11-28 12:42

    Due to the lack of events available for elements, there is no way to a selection from the suggestions other than watching the input's events (change, input, etc). Also see my answer here: Determine if an element was selected from HTML 5 datalist by pressing enter key

    To check if a selection was picked from the list, you should compare each change to the available options. This means the event will also fire when a user enters an exact value manually, there is no way to stop this.

    document.querySelector('input[list="items"]').addEventListener('input', onInput);
    
    function onInput(e) {
       var input = e.target,
           val = input.value;
           list = input.getAttribute('list'),
           options = document.getElementById(list).childNodes;
    
      for(var i = 0; i < options.length; i++) {
        if(options[i].innerText === val) {
          // An item was selected from the list!
          // yourCallbackHere()
          alert('item selected: ' + val);
          break;
        }
      }
    }
    
    
      
      
    

提交回复
热议问题