问题
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