选定的< datalist>的值物品 [英] Value of selected <datalist> item
问题描述
我正在使用<input type='text'>
元素和<datalist>
来为表单提供用户名建议.一切正常,我的所有用户都出现了.
I am using a <input type='text'>
Element together with a <datalist>
to provide user name suggestions for a form. Everything works as expected and all my user show up.
但是,当用户提交表单时,我想根据输入在我的数据存储中选择合适的用户.不幸的是,名字不是唯一的,并且有可能重复.为避免这种情况,我所有的用户都有一个唯一的ID,该ID也是<datalist>
的<options>
标记的一部分.
However, when the user submits the form I would like select the right user in my data storage based on the input. Unfortunately, names are not unique and there is a chance for duplicates. To avoid this, all my users have a unique ID that is also part of the <datalist>
's <options>
tags.
除了输入的文本值之外,还有什么方法可以读取其他内容?是否有对所选数据列表元素的引用?我可以根据文本输入检索用户的ID吗?
Is there any way I can read anything else but the input's text value? Is there a reference to the selected datalist element? Can I retrieve a user's id based on the text input?
<input type="text" class="form-control" name="userName" placeholder="Type a user's name" value="" list="user-datalist" required autofocus>
<datalist id="user-datalist">
<option id="53c911ea609252c600632dfe" value="Mr Smith">Mr Smith</option>
<option id="53c911ea60925sdfs4e444eg" value="John Snow">John Snow</option>
<option id="53c911ea6034534535k345th" value="John Snow">John Snow</option>
<option id="53c911ea60925234234234er" value="Mickey Mouse">Mickey Mouse</option>
</datalist>
推荐答案
您所说的名称不是唯一的.所以我在您的数据列表中添加了一个重复的名称.
As you said name are not unique. so i have added a duplicate name to your datalist.
<input type="text" class="form-control" name="userName" placeholder="Type a user's name" value="" list="user-datalist" required autofocus>
<datalist id="user-datalist">
<option id="53c911ea609252c600632dfe" value="Mr Smith">Mr Smith</option>
<option id="53c911ea60925sdfs4e444eg1" value="John Snow">John Snow</option>
<option id="53c911ea60925sdfs4e444eg2" value="John Snow">John Snow</option>
<option id="53c911ea60925234234234er" value="Mickey Mouse">Mickey Mouse</option>
</datalist>
<input type="button" id="sub" value="sub"/>
并获取名称的ID
$('#sub').on('click',function(){
var g=$('input[type="text"]').val();
var id = $('#user-datalist').find('option').filter(function() { return $.trim( $(this).text() ) === g; }).attr('id');
alert(id);
});
这篇关于选定的< datalist>的值物品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!