如何在数据列表中获取数据值

时间:2016-10-24 09:15:29

标签: html

如何在datalist中获取数据值? 例如:

<datalist id="browsers">
   <option value="Internet Explorer" data-value="1">
   <option value="Firefox" data-value="2">
   <option value="Chrome" data-value="3">
   <option value="Opera" data-value="4">`enter code here`
   <option value="Safari" data-value="5">
</datalist>

3 个答案:

答案 0 :(得分:1)

这对我有用:

function getDataListSelectedOption(txt_input, data_list_options) 
{
var shownVal = document.getElementById(txt_input).value;
var value2send = document.querySelector("#" + data_list_options + " option[value='" + shownVal + "']").dataset.value;
            return value2send;
}

txt_input是文本框的id txt_data_list_option是data_list

的id

希望它有所帮助。

答案 1 :(得分:0)

试试这个

        <datalist  id="browsers">
    <option value="Internet Explorer" data-value="1">
    <option value="Firefox" data-value="2">
    <option value="Chrome" data-value="3">
    <option value="Opera" data-value="4">`enter code here`
    <option value="Safari" data-value="5">
</datalist>

<input type="text" name="located" list="browsers"/>

答案 2 :(得分:0)

这对我有用

HTML代码

 <input list="newBrwosers" id="newBrwoser" name="newBrwoser" class="form-control">
<datalist  id="newBrwosers">
<option value="Internet Explorer" data-value="1" data-id="1">
<option value="Firefox" data-value="2" data-id="2">
<option value="Chrome" data-value="3" data-id="3">
<option value="Opera" data-value="4" data-id="4">`enter code here`
<option value="Safari" data-value="5" data-id="5">
</datalist>

JS代码

 var newBrwoser= document.getElementById("newBrwoser").value;
 var newBrwoser_val= document.querySelector("#newBrwosers"  + " option[value='" + newBrwoser+ "']").dataset.value;
 var newBrwosers_id= document.querySelector("#newBrwosers"  + " option[value='" + newBrwoser+ "']").dataset.id;