How to get the text value of a selected item from a DataList using jQuery

谁都会走 提交于 2021-02-11 12:12:11

问题


How do I get the text value of the options in a DataList? I need to make use of the value of an id, But I also need the value of the selectedIndex, which is the name.

<input type="text" name="names[]" id="names" list="neym"/>
<datalist id="neym">
    <option value="example"></option>
    <option value="example2"></option>
    <option value="example3"></option>
</datalist>

How do I do that in jQuery?


回答1:


Loop through them and use text() and val() as others have pointed out:

$('#neym option').each(function(index) {
    var id = $(this).val();
    var name = $(this).text();

    // Do something with the id and name
    alert('Found ' + name + ' with id ' + id);
});



回答2:


For getting selected index's text

$("#neym option:selected").text()

For getting selected index's value

$('#neym').attr('value')



回答3:


To get the text inside the selected option

$( "#neym :selected" ).text();

Or to get it's value

$( "#neym :selected" ).val()



回答4:


<input id="option_box" list="my_options">
<datalist id="my_options">
</datalist>

document.getElementById('option_box').value;

The input element holds the value of the selected field in the datalist. This is a simple non jquery version of the answer.



来源:https://stackoverflow.com/questions/6571158/how-to-get-the-text-value-of-a-selected-item-from-a-datalist-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!