首页 > 解决方案 > How to determine selected datalist option

问题描述

Is there way to determite, which option from datalist was selected? I mean when I have duplicite names in datalist, see example below:

<input type="text" list="cities" id="search-bar" name="city" value="" autocomplete="off" placeholder="type city">
<datalist id="cities">
        <option value="Olo (PT)" data-city-index="0"></option>
        <option value="Olo (PT)" data-city-index="1"></option>
        <option value="Olonets" data-city-index="2"></option>
        <option value="Olot" data-city-index="3"></option>
</datalist>

It is part of weather app, and in some countries, there are cities with same name (but different location) - so how I can distinguih if user have clicked on first or second Olo in example? Is it even possible? I have idea, that maybe is there way to use data attribute, but I dont know if it actually solve my problem (and how...)

Please help.

EDIT: I understand, that it is for user little bit uncomfortable to actually "don't know" which city they are selecting in datalist, but unfortunatelly I have no way to "help" them (I have only database with city names and longitude and latitude of it). So after selection of city I include link to google maps (for that location) to displaying part

标签: javascripteventshtml-inputhtml-datalist

解决方案


您应该更改城市名称中选项的值国家。当用户点击列表时

<input type="text" list="cities" id="search-bar" name="city" value="" autocomplete="off" placeholder="type city">
<datalist id="cities">
        <option value="city1 (PT)" data-city-index="0"></option>
        <option value="city2 (PT)" data-city-index="1"></option>
        <option value="city3" data-city-index="2"></option>
        <option value="city4" data-city-index="3"></option>
</datalist>


推荐阅读