Home >Web Front-end >JS Tutorial >How Do I Retrieve the Selected Option's Value or Text from a jQuery Dropdown?
When using $("#id").val() to return the value of a selected option in a dropdown, one may encounter unexpected results. This is due to a specific scenario involving the element ID and the nature of dropdown options.
In html code, where the element with ID aioConceptName represents a dropdown, the following code will not work as intended:
$('#aioConceptName').val()
The reason for this is that val() retrieves the value attribute of the dropdown itself, not the selected option within it. To obtain the value or text of the selected option, use the following approach:
For Selected Text:
var conceptName = $('#aioConceptName').find(':selected').text();
This code locates the selected option within the dropdown using the :selected selector and retrieves its text.
For Selected Value:
var conceptName = $('#aioConceptName').find(':selected').val();
This code similarly locates the selected option but returns its value attribute.
The above is the detailed content of How Do I Retrieve the Selected Option's Value or Text from a jQuery Dropdown?. For more information, please follow other related articles on the PHP Chinese website!