jQuery event for HTML5 datalist when item is selected or typed input match with item in the list

我怕爱的太早我们不能终老 提交于 2019-12-03 18:49:28

问题


I have datalist like below -

<input id="name" list="allNames" />
<datalist id="allNames">
    <option value="Adnan1"/>  
    <option value="Faizan2"/>   
</datalist>

What I want is, when an item is typed in completely(for example say in input box when user completely type "Adnan1") or selected from list, then I want an event. I tried couple of approaches but both doesn't help me so far. Approaches are -

$("#name").change(function(){
console.log("change");
}

problem with this is, the event only gets triggered when input gets out of focus I.e. when I click somewhere in the screen.

I also tried

$("#name").bind('change', function () {
    console.log('changed'); 
});

but the callback gets triggered each time when I type in. I actually need to make an AJAX call when item is completely selected. Either via type-in or by selecting from dropdown.

First approach is bad for user perspective because he has to make extra click and second has disadvantage as for every letter an event will be triggered.

All I want is an event when either user made a selection or typed complete sentence. is there a way to achieve this? any event that I missing and that can solve my problem.


回答1:


On modern browsers, you can use input event, e.g:

$("#name").on('input', function () {
    var val = this.value;
    if($('#allNames option').filter(function(){
        return this.value.toUpperCase() === val.toUpperCase();        
    }).length) {
        //send ajax request
        alert(this.value);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input id="name" list="allNames" />
<datalist id="allNames">
    <option value="Adnan1" />
    <option value="Faizan2" />
</datalist>

PS: as input event has better support than datalist element, there is indeed no reason to not use it if you are already using datalist element.




回答2:


You can use input event for achieving such functionality, as below :

$(document).ready(function() {
  $('#name').on('input', function() {
    var userText = $(this).val();

    $("#allNames").find("option").each(function() {
      if ($(this).val() == userText) {
        alert("Make Ajax call here.");
      }
    })
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" list="allNames" />
<datalist id="allNames">
  <option value="Adnan1" />
  <option value="Faizan2" />
</datalist>



回答3:


Simple solution

document.getElementById('name').addEventListener('input', function () {
   console.log('changed'); 
});



回答4:


Check if this works for you :

var dataList=[];
$("#allNames").find("option").each(function(){dataList.push($(this).val())})
console.log(dataList);
$("#name").on("keyup focus blur change",function(){
    if(dataList.indexOf($(this).val())!=-1)
console.log("change");
})

I pushed datalist options into array , and on change event keyup , blur or focus , i check if input value exists in my datalist array.




回答5:


Hacky as a sin, but works for me. (Note that if you are typing 'Rum-Cola' it doesn't stop on the 'Rum' option)

const opts = $("option").map(function(){return  this.value;}).get();

$("#favourite-drink").on("keydown", function(e){
  if(e.key){ // in case of mouse event e.key is 'undefined'
    if (e.key === "Enter") { // looks like user wants to confirm the choice
      if(opts.indexOf(this.value) >= 0){
        this.blur();
        console.log("Selected: " + this.value);
      }
    }
    else {
      this.setAttribute("data-keyboardinput", "true"); // remember that it's keyboard event

      setTimeout(function(){ //and keep it in memory for 100ms
        this.removeAttribute("data-keyboardinput")
      }.bind(this), 100);
    }
  }
});

$("#favourite-drink").on("input", function(){
  if(!this.dataset.keyboardinput && opts.indexOf(this.value) >= 0){ // if it's not a key press followed event
    console.log("Selected: " + this.value);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Choose a drink:</p>
  <input id="favourite-drink" list="drinks">
  <datalist id="drinks">
    <option value="Rum"></option>
    <option value="Rum-Cola"></option>
    <option value="Vodka"></option>
  </datalist>


来源:https://stackoverflow.com/questions/30151633/jquery-event-for-html5-datalist-when-item-is-selected-or-typed-input-match-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!