如何获得在javascript中datalist内选定项目的值? [英] How to get the value of selected item inside datalist in javascript?
问题描述
我的列表是通过php生成的:
< input name =txt_namelist =emp_namesautocomplete = offid =txt_nameclass =textboxonchange =getID(emp_names.text);/>
< datalist id =emp_names>
<?php
$ host =localhost;
$ user =root;
$ pass =mark;
$ db =payrolldb;
$ cons = mysql_connect($ host,$ user,$ pass);
mysql_select_db($ db,$ cons);
//查询开始
$ query =SELECT ID_Employee,CONCAT(LastName,',',FirstName)AS Name,Department FROM tbl_employeeInfo;;
$ result = mysql_query($ query);
while($ row = mysql_fetch_array($ result))
{
echo< option value ='。$ row ['Name']。'>。$ row [ 'ID_Employee'] < /选项> \\\
。
}
?>
< / datalist>
它显示出这样。
每个的选项具有文本值,该值是图像中的15。
选项本身的值是Mehta,Jack
我想知道如何获取文本值并从javascript函数中传递它。
我尝试在输入和datalist标记中使用onchange方法。
但它说不准备属性文本为'undefined'。
这是我使用JQuery做到这一点的最佳方式。 b
$ b
var selection = $(#txt_name)。val();
var text = $(#emp_names option)。filter(function(){return this.value == selection;})。text();
您必须将该函数放在输入的input输入事件中,而不是数据输入。只要你选择了这个选项,它就会启动。如果您使用onchange事件,它只会在您失去焦点或blur()发生后触发。
My list is generated via php:
<input name="txt_name" list="emp_names" autocomplete="off" id="txt_name" class="textbox" onchange="getID(emp_names.text);"/>
<datalist id="emp_names">
<?php
$host = "localhost";
$user = "root";
$pass = "mark";
$db = "payrolldb";
$cons = mysql_connect($host,$user,$pass);
mysql_select_db($db,$cons);
//query start
$query = "SELECT ID_Employee, CONCAT(LastName,', ',FirstName) AS Name, Department FROM tbl_employeeInfo;";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['Name']."'>".$row['ID_Employee']."</option>\n";
}
?>
</datalist>
And it shows up like this.
Each of the options has a text value, which is "15" from the image. the value of the option itself is "Mehta, Jack"
I wanted to know how to get the text value and to pass it from a javascript function.
I tried using an onchange method in both the input and the datalist tag.
But it says Cannot ready property text of 'undefined'.
This is the best way I have found to do this using JQuery
var selection = $("#txt_name").val();
var text = $("#emp_names option").filter(function () { return this.value == selection; }).text();
You have to put the function on the oninput event of the input NOT the datalist. This will fire as soon as you pick the selection. if you use onchange event it will only fire after you lose focus or the blur() happens.
这篇关于如何获得在javascript中datalist内选定项目的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!