Home > Web Front-end > JS Tutorial > How to Select a Drop-Down Option by Its Text Description with jQuery?

How to Select a Drop-Down Option by Its Text Description with jQuery?

DDD
Release: 2024-11-03 06:38:03
Original
740 people have browsed it

How to Select a Drop-Down Option by Its Text Description with jQuery?

Setting Selected Drop-Down Option by Text Description with jQuery

In the realm of web development, selecting an element within a select control based on its text description often arises. While setting an option by its value is straightforward, finding the corresponding value for a given text description can be a challenge.

Genesis of the Query

The need for this functionality stems from the situation where a JavaScript variable holds a text string, and the aim is to select the drop-down option whose text matches this string. Unlike the value-based selection, which utilizes the $("#my-select").val(myVal) syntax, this task requires a more intricate approach.

Resolving the Enigma

For jQuery versions 1.6 and above, the solution lies in leveraging the filter() and prop() methods. The filter() method sifts through all options within the select control, comparing their text descriptions to the desired string. The resulting element is then targeted by the prop() method, setting its selected attribute to true.

Example Implementation

Consider a select control with two options: 'One' and 'Two'. The following code illustrates how to select the option with the text 'Two' using the text-based approach:

<code class="javascript">var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).prop('selected', true);</code>
Copy after login

This code effectively selects the 'Two' option within the drop-down list based on its text description, even without knowing its value.

The above is the detailed content of How to Select a Drop-Down Option by Its Text Description with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template