Nono Nono - 1 year ago 145
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">
foreach($cities as $city){
echo '<option value="'.$city.'" />';

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


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

Answer Source

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.

   var option = $('#cities option').filter(function() {
       return this.value === $("#city").val();
   if(option) $("#output").html("Match Found:"+ option)
   else $("#output").html("");
  margin-top: 30px;
<script src=""></script>

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download