简体   繁体   English

Javascript:根据输入匹配datalist选项

[英]Javascript: Match datalist options based on input

I have a text input with a datalist. 我有一个带有datalist的文本输入。 This datalist is filled dynamic with php: 这个datalist用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? 有没有一种简单的方法来存储javascript数组中的所有datalist选项?

EDIT: 编辑:

Or better: Is there a way to check with javascript if the text in the input field is an option in the datalist? 或者更好:如果输入字段中的文本是数据列表中的选项,是否有办法检查javascript?

就在这里:

var cities = <?=json_encode($cities)?>;

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. 如果你没有转换为json数组并运行javascript匹配,你可以很容易地在JavaScript中执行此操作。

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. 您可以更改过滤器函数的return部分以进行任何类型的匹配。

 $("#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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM