Nono Nono - 4 months ago 29
Javascript Question

Javascript: Match datalist options based on input

I have a text input with a datalist. This datalist is filled dynamic with php:

<input type="text" name="city" list="cities" id="city">
<datalist id="cities">
<?php
foreach($cities as $city){
echo '<option value="'.$city.'" />';
}
?>
</datalist>
</input>


Is there an easy way to store all datalist options in a javascript array?

EDIT:

Or better: Is there a way to check with javascript if the text in the input field is an option in the datalist?

Answer

Answer for your "Or Better Part"

It should be pretty easy to do this just in JavaScript as you ask without converting to json array and running javascript match.

Attached a example snippet. Here's the example that checks if value being typed in input matches any of the options or not.

Here's what it does, on each keyup on input, it checks if there is a option in the datalist that matches the input user entered. You can change the return part of filter function to do any kind of matching.

$("#city").on('keyup',function(e){
   var option = $('#cities option').filter(function() {
       return this.value === $("#city").val();
   }).val();
  
   if(option) $("#output").html("Match Found:"+ option)
   else $("#output").html("");
});
#output{
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" list="cities" id="city">

<datalist id="cities">
  <option value="Volvo">
  <option value="Saab">
  <option value="Mercedes">
  <option value="Audi">
</datalist>

<span id="output"></span>