Home >Web Front-end >JS Tutorial >How to Retrieve Option Text Based on Value in jQuery?

How to Retrieve Option Text Based on Value in jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 02:32:02731browse

How to Retrieve Option Text Based on Value in jQuery?

Retrieving Option Text by Value in jQuery

In the realm of web development, extracting specific information from elements is a common task. In jQuery, we can leverage the power of selectors to accomplish this effortlessly.

Consider a scenario where you have a drop-down list defined as:

<code class="html"><select id="list">
    <option value="1">Option A</option>
    <option value="2">Option B</option>
    <option value="3">Option C</option>
</select></code>

The objective is to retrieve the text of the option with a specific value (e.g., "2"), regardless of whether it's selected. Using a selector like "$("#list[value='2']").text();" won't yield the desired result.

Solution 1: Targeting a Specific Option

To get the text of the option with a specific value, employ the following selector:

<code class="javascript">$("#list option[value='2']").text();</code>

Solution 2: Getting the Selected Option

Alternatively, if you wish to retrieve the text of the currently selected option, use this selector:

<code class="javascript">$("#list option:selected").text();</code>

By leveraging these selectors, you can conveniently extract the desired option text, empowering you with precise control over your web applications.

The above is the detailed content of How to Retrieve Option Text Based on Value in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn