37

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
  • not to be mean but HTML5 Datalist isn't support by all browers Commented Dec 1, 2017 at 15:01

7 Answers 7

60

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.

5
  • 1
    This causes issues when you options have similar values (an option could be a substring of another) or numbers, and several options could fit the result. I.E. 1 and 10 as options would never work as you cannot type 10. As soon as the 1 is entered, then that option is selected. Ben and Benjamin is another example. Commented Dec 13, 2017 at 15:19
  • @AndrewStalker I'm not sure on each browser do you see this behaviour but as i understand your comment, it works as expected on chrome. The issue you describe could be because of the modal behaviour of alert() (safari would be affected by it AFAIK). Can you test using console instead: jsfiddle.net/bsyo2vdo/384 Do you facing same issue? If still, could you tell me how to replicate this issue exactly?
    – A. Wolff
    Commented Dec 13, 2017 at 16:25
  • 2
    Yes this still happens with the console output (on Chrome). Using your jsfiddle, as soon as i type 1 the console logs 1. IRL if you intended to type 10 it's now too late as the ajax event has fired for 1. Commented Dec 13, 2017 at 18:05
  • @AndrewStalker Ok i see what you mean. Generally to handle this case of behaviour, we debounce the ajax request to let user enough time if still typing as e.g: jsfiddle.net/bsyo2vdo/385 BUT it appears not to be a so good solution here. It would be simpler if the datalist could handle mouse events but it is not the case on chrome. When i'll have more time, i'll try to find a better way but i'm really not sure i could find any, unfortunately...
    – A. Wolff
    Commented Dec 13, 2017 at 19:52
  • Ah I see, that makes sense. Thanks Commented Dec 14, 2017 at 8:59
8

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>

4
  • 1
    This isn't fired if item selected from dropdown list
    – A. Wolff
    Commented May 10, 2015 at 13:16
  • @A.Wolff It seems, input even is the only way then ?
    – Ankit
    Commented May 10, 2015 at 13:20
  • 1
    Not sure but i'm guessing ya, because e.g on chrome (don't know for other browsers), you cannot bound event to datalist element. Now it could have some dirty workarounds but...
    – A. Wolff
    Commented May 10, 2015 at 13:21
  • 1
    This is a buggy workaround that will cause errors with some input datasets. For example, if you have a list with four names, "Fred", "Freddy", "Fredman", and a user wants to type "Fredman", it will submit after the first four characters are typed since it matches "Fred". Commented Mar 24, 2016 at 20:25
1

Simple solution

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

Simple solution is that check the input text value exist in datalist or not, and if it does, run an ajax request.

$("#input_form").on('input', function(event){
   if ($("#input_datalist option[value='" + $('#input_form').val() + "']").val() != undefined) {
      //send ajax request
   }
});
0

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>

0

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.

0

In addition to what was said above, we can also check the inputType of the input which must correspond to "insertReplacementText"

function textThatComesFromADatalist (event){
    const inputType = event.inputType;
    const isReplacingText = (typeof inputType === "undefined")
        || (inputType === "insertReplacementText");
    return isReplacingText;
}

function onInput(event) {
  if(textThatComesFromADatalist(event)){
    alert('selected: '+event.target.value);
  }
}
<input  oninput="onInput(event)" list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
</datalist>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.